使用python的paramiko
包可以登陆远程机
或网络设备
(只要该机器支持ssh登陆),并对远程机进行shell命令操作,因此可以使用paramiko来验证远程机的ssh
是否连通。
具体代码示例如下:
#! /usr/bin/python
import commands
import threadpool
import time
import paramiko
# config
# thread config
thread_num = 40
# ssh config
ssh_port = 22
ssh_username = r'xxxxxx'
ssh_password = r'xxxxxx'
# input file
ips_file = './ips.txt'
# output file
ssh_success_file = './ssh_success.txt'
ssh_faild_file = './ssh_faild.txt'
# output
success_list = list()
faild_list = list()
with open(ips_file, 'r') as fip:
ips = [x.replace('\n', '').replace('\r', '') for x in fip.readlines()]
ips = [ip for ip in ips if ip is not '' and ip is not None]
def domain(ip):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=ip, port=ssh_port, username=ssh_username, password=ssh_password, timeout=5, look_for_keys=False, allow_agent=False)
success_list.append(ip)
except Exception as e:
print e
faild_list.append((ip, e))
finally:
client.close()
if __name__ == '__main__':
pool = threadpool.ThreadPool(thread_num)
requests = threadpool.makeRequests(domain, ips)
[pool.putRequest(req) for req in requests]
pool.wait()
with open(ssh_success_file, 'w') as fs:
for ip in success_list:
fs.write(ip + '\n')
with open(ssh_faild_file, 'w') as ff:
for ip, e in faild_list:
ff.write(str(ip) + ',' + str(e) + '\n')
由于控制端往往是要控制多台设备,所以这里使用多线程的方式。具体可参考《python实现多线程发送网络请求——基础模板》。