使用第三方库paramiko实现ssh远程登录服务器执行巡检命令
由于脚本包含明文密码所以使用Pyinstaller模块转成exe文件
# coding=UTF-8
import paramiko
import sys
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
s.connect("192.40.0.1",22,"root", "password1")
execmd = ["dcli -l root -g all_group 'date'"] #需要输入的命令
mylog = open('xjlog.txt','a')
for i in execmd:
stdin, stdout, stderr = s.exec_command (i)
# print(stdout.read())
print >> mylog,stdout.read()
mylog.write("-----------------------------------------\n")
mylog.close()
#with open('xjlog.txt') as f: # 默认模式为‘r’,只读模式
# contents = f.read() # 读取文件全部内容
# print contents
s.close()
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
s.connect("192.40.1.1",22,"root", "password1")
execmd = ["dcli -l root -g all_groups 'date'"] #需要输入的命令
mylog = open('xjlog.txt','a')
for i in execmd:
stdin, stdout, stderr = s.exec_command (i)
# print(stdout.read())
print >> mylog,stdout.read()
mylog.write("-----------------------------------------\n")
mylog.close()
with open('xjlog.txt') as f: # 默认模式为‘r’,只读模式
contents = f.read() # 读取文件全部内容
print contents
s.close()
参考:
https://www.cnblogs.com/sch01ar/p/8024380.html
https://www.cnblogs.com/vijing/p/10415124.html
https://www.cnblogs.com/xiao-apple36/p/9144092.html
http://c.biancheng.net/view/2690.html