「python初心者」Linuxコマンドまた設定内容をバッチ実行する

ファイル名:startnews24_exec.py
pythonコード:
#!/bin/env python
import paramiko
import sys,os
import time
from optparse import OptionParser

parser = OptionParser(add_help_option=0)
parser.add_option(“-f", “–file", action="store", type="string", dest="listfile",default="")
parser.add_option(“-u", “–user", action="store", type="string", dest="username",default="root")
parser.add_option(“-p", “–passwd", action="store", type="string", dest="password",default="mypass")
parser.add_option(“-P", “–port", action="store", type="string", dest="port",default="22″)
parser.add_option(“-c", “–cmd", action="store", type="string", dest="cmdline",default="hostname")
parser.add_option(“-s", “–script", action="store", type="string", dest="script",default="")

(options, args) = parser.parse_args()

listfile=options.listfile
username = options.username
passwd = options.password
port = options.port
rcmd = options.cmdline
scriptfile = options.script
time_now = time.strftime('%Y%m%d%H%M%S’)

infofile="log/info_startnews24.txt"
if os.path.isdir(“log"):
pass
else:
os.mkdir(“log")
if os.path.isfile(infofile):
os.rename(infofile,infofile+time_now)
info = open(infofile,"a")
#コマンドを実行
def execmd(host,port,username,passwd,rcmd):
#info = open(infofile,"a")
try:
client = paramiko.SSHClient()
#client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(host,port=int(port),username=username,password=passwd,timeout=1)
#rcmd = “ifconfig eth0|grep HWaddr|awk '{print $NF}'"
print rcmd
stdin, stdout, stderr = client.exec_command(rcmd)
#info.write(host+"\n"+"@"*20+"\n")
for line in stdout:
info.write(“%s: %s"%(host,line))
client.close()
except:
info.write(“%s: SSHログイン失敗した\n\n"%(host))
#info.close()
#ファイルを翻訳
def transfile():
try:
trans = paramiko.Transport((host,int(port)))
trans.connect(username=username,password=passwd)
sftp = paramiko.SFTPClient.from_transport(trans)
#sftp.get(“","")
sftp.put(scriptfile,"/tmp/%s"%scriptfile)
trans.close()
except:
#print “File translation faild"
info.write(“%s: File translation faild\n"%(host))

if __name__=="__main__":
for ipaddr in open(listfile).readlines():
host = ipaddr.strip(“\n").rstrip().lstrip()
print host
if scriptfile == “":
pass
else:
transfile()
rcmd="sh /tmp/%s"%scriptfile
execmd(host,port,username,passwd,rcmd)
info.close()

Python

Posted by arkgame