需要模块:paramiko
pip3 install paramiko
import paramiko
import sys
import getpass
def rcmd (host,password,cmd,port=22,username='root'):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #
ssh.connect(host,username=username,password=password,port=port)
stdin,stdout,stderr = ssh.exec_command(cmd) #分别保存,标准输入,标准输出,错误输出
data = stdout.read().decode('utf8')
error = stderr.read().decode('utf8')
if data:#如果存标准输出,打印
print('[%s:OUT]:\n%s' % (host,data))
if error:
print('[%s:ERROR]:\n%s' % (host,error))
ssh.close()
if __name__ == '__main__':
# rcmd('192.168.4.11','123456','useradd zzz')
password = getpass.getpass()
ips = sys.argv[1]
with open(ips) as fobj: #循环导入地址
for lines in fobj:
ip = lines.strip()
rcmd(ip,password,sys.argv[2])
多线程优化版:
import paramiko
import sys
import getpass
import threading
import os
def rcmd (host,password,cmd,port=22,username='root'):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #
ssh.connect(host,username=username,password=password,port=port)
stdin,stdout,stderr = ssh.exec_command(cmd) #分别保存,标准输入,标准输出,错误输出
data = stdout.read().decode('utf8')
error = stderr.read().decode('utf8')
if data:#如果存标准输出,打印
print('[%s:OUT]:\n%s' % (host,data))
if error:
print('[%s:ERROR]:\n%s' % (host,error))
ssh.close()
if __name__ == '__main__':
if len(sys.argv) != 3:
print('%s 参数使用不正确' % (sys.argv[0]))
exit(1)
password = getpass.getpass()
ips = sys.argv[1]
cmd = sys.argv[2]
if not os.path.isfile(ips):
print('找不到文件!',ips)
exit(2)
with open(ips) as fobj: #循环导入地址
for lines in fobj:
ip = lines.strip()
t = threading.Thread(target=rcmd,args=(ip,password,cmd))
t.start()