在实际维护环境中或者在AWD比赛中可能会用到SSH批量连接的需求,下面这段批量连接代码分享给大家,大家可以在这个基础上面继续加工比如修改密码。
#coding:utf-8
import paramiko
import time
#pkey = paramiko.RSAKey.from_private_key_file('C:\\Users\id_rsa')
def ssh_conn(ssh_ip, command):
ip = ssh_ip
port = '22'
user = 'root'
passwd = '123456'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=ip, port=port, username=user, password=passwd,timeout=3)
except:
print('[INFO] host: %s auth failed' % ip)
try:
stdin, stdout, stderr = client.exec_command(command)
result = stdout.read().decode('utf-8')
print(ssh_ip)
print(result)
except:
pass
client.close()
if __name__ == "__main__":
command = "ifconfig"
for j in range(1, 129):
if j != 129:
ssh_ip = '192.168.1.' + str(j)
ssh_conn(ssh_ip , command)