def sshRunCmd(hostname, username, password, cmdlist):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 創建ssh連接
client.connect(hostname=hostname, port=22, username=username, password=password)
# 開啟ssh管道
ssh = client.get_transport().open_session()
ssh.get_pty()
ssh.invoke_shell()
# 執行指令
for cmd in cmdlist:
ssh.sendall(cmd)
time.sleep(2)#因為執行的命令比較多,不想把這個sleep時間弄的太長,我試過sleep調到10分鐘就沒有問題
#我就想在這里加個判斷,如果上面的東西執行完畢了(也就是不再繼續產生內容了),那么就往下進行,否則就等待,遠程主機可能是多種比較蠢的設備,執行各種命令,無法用結尾字符來判斷,比如執行ping -c 100 8.8.8.8,我想的方式是N秒沒有新的資料就繼續往下走
result = ssh.recv(102400)
result = result.decode(encoding='UTF-8', errors='strict')
print(result)
f = open(path + '/' + hostname +'_'+ today + ".txt", "a")
#f.write("111 ")
f.write(result)
f.close()
except Exception as e:
print("[%s] %s target failed, the reason is %s" % (datetime.datetime.now(), hostname, str(e)))
else:
print("[%s] %s target success" % (datetime.datetime.now(), hostname))
finally:
ssh.close()
client.close()
#我就想在這里加個判斷,如果上面的東西執行完畢了(也就是不再繼續產生內容了),那么就往下進行,否則就等待,遠程主機可能是多種比較蠢的設備,執行各種命令,無法用結尾字符來判斷,比如執行ping -c 100 8.8.8.8,我想的方式是N秒沒有新的資料就繼續往下走
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/126242.html
