python的paramiko模块
下面代码完成了以下功能:
- 扫描可用ip
- 监控指定网卡的状态
#!/usr/bin/python3
import paramiko
import time
class SSHConnection(object):
# 初始化主机名称、ip、端口等信息
def __init__(self, hostname, username, password, port=22):
#ssh相关属性
self.hostname = hostname
self.username = username
self.password = password
self.port = port
self.ssh = paramiko.SSHClient()
#网卡相关属性
self.ip = ""
self.status = ""
# 连接远程服务器
def connect(self):
self.ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy()) # #####################允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
self.ssh.connect(hostname=self.hostname, username=self.username, password=self.password, port=self.port)
# 关闭连接
def close(self):
self.ssh.close()
# 得到ping某台host的平均延迟
def ping(self, ip):
ret_ping = self.cmd('ping -c 5 -w 5 ' + ip + r' | grep icmp | egrep -o "[0-9]\.[0-9]*\ ms" | cut -d" " -f1')
ret_ping = str(ret_ping)[2:-1]
latencys_str = ret_ping.split(r"\r\n")
sum_latency = 0.0
count = 0
for latency_str in latencys_str:
if latency_str != '':
sum_latency += float(str(latency_str))
count += 1
if count == 0:
return 0 # 不可达则返回0
return round(sum_latency / count, 2) # 得到平均延迟
# 判断哪些机器ping可达
# 这里改成并发会更好
def detect(self, ip_prefix):
hosts = {}
for i in range(1, 255):
ip = ip_prefix + str(i)
ret_ping = self.ping(ip)
if ret_ping != 0:
hosts[ip] = ret_ping
# 所有可达机器:
print("所有可达机器:")
for host in hosts:
print(host)
# 最慢的节点
n = 5
if len(hosts) < 5:
n = len(hosts)
print("\n最慢的节点:")
hosts = sorted(hosts.items(), key=lambda x: x[1], reverse=True)
# print(hosts) # debug
for i in range(n):
print(hosts[i][0], hosts[i][1])
# 得到网卡的ip和状态
# 这里只拿ipv4地址了
def get_nc_status(self,nc_name):
ip = self.cmd('nmcli device show '+nc_name+" | grep IP4.ADDRESS | awk '{print $2}' | cut -d'/' -f1")
status = self.cmd("nmcli device show " + nc_name + " | grep GENERAL.STATE | awk '{print $3}'")
return ip,status
# 定时检查网卡状态
def check_nc(self, nc_name, sleep_time):
self.ip, self.status = self.get_nc_status(nc_name)
while True:
time.sleep(sleep_time)
ip, status = self.get_nc_status(nc_name)
if self.ip != ip:
print("ip发生变化,从%s变成了%s" % (self.ip, ip))
self.ip = ip
print()
if self.status != status:
print("status发生变化,从[%s]变成了[%s]\n" % (self.status, status))
self.status = status
# 执行命令
def cmd(self, command):
stdin, stdout, stderr = self.ssh.exec_command(command, get_pty=True)
result = stdout.read()
return result
if __name__ == '__main__':
hostname = '172.16.1.131'
username = 'root'
password = '1'
port = 22
# 连接
myssh = SSHConnection(hostname, username, password, port)
try:
myssh.connect()
except paramiko.ssh_exception.AuthenticationException as exception:
print("连接失败:", exception)
# 机器探测
# myssh.detect("127.0.0.")
# 定时检查网卡ip和状态
# print(myssh.get_nc_status("ens160")) #debug
try:
myssh.check_nc("ens160", 3)
except KeyboardInterrupt:
myssh.close()
# myssh.cmd("pwd") # 得到b'/root\r\n'