基于 python 的多终端 ssh 操作程序
直接可用代码,配置 ssh_info 文件到当前目录
ssh_info 如下:
# ip及账号密码定义
#| ip |port|user|password
192.168.1.1|22|root|12345678
192.168.1.2|22|root|12345678
运行程序代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import sys
from concurrent.futures import ThreadPoolExecutor
import threading
import time
import threadpool
import os
import re
def ssh_connect(ipInfos):
sshList = []
for info in ipInfos:
ssh = paramiko.SSHClient() # 创建SSH对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
print("Start connect to ", info['ip'], info['port'], info['username'], info['password'])
ssh.connect(hostname=info['ip'], port=info['port'], username=info['username'],
password=info['password']) # 连接服务器
print("Connect to ", info['ip'], " success!")
sshList.append(ssh)
return sshList
def ssh_close(sshInfos):
for ssh in sshInfos:
ssh.close()
print("关闭链接:", ssh.info)
# ssh执行模式
def ssh_exec(sshInfos, command):
for ssh in sshInfos:
# print("Command on ", ssh.get_ip())
stdin, stdout, stderr = ssh.exec_command(command, get_pty=True) # 执行命令并获取命令结果
# stdin为输入的命令
# stdout为命令返回的结果
# stderr为命令错误时返回的结果
res, err = stdout.read(), stderr.read()
result = res if res else err
result = result.decode()
result = result.replace('\r\n', '')
print(ssh.get_transport(), " return Info : ", result)
time.sleep(2)
# 读取配置文件
def ssh_info_from_file(filename):
setting_file = open(filename, "r", encoding='utf-8')
hostInfos = []
for line in setting_file:
if re.match(r".*(?:[0-9]{1,3}\.){3}[0-9]{1,3}.*", line):
hostInfo = line.split("|")
hostinfoDetail = {};
hostinfoDetail["ip"] = hostInfo[0].replace(' ', '')
hostinfoDetail["port"] = hostInfo[1].replace('', '')
hostinfoDetail["username"] = hostInfo[2].replace('', '')
hostinfoDetail["password"] = hostInfo[3].replace('\n', '')
print(hostInfo[3])
hostInfos.append(hostinfoDetail)
# print(hostinfoDetail)
else:
# print("The file you specified is not correct")
continue
# print(line)
return hostInfos
if __name__ == "__main__":
# 查找文件信息,返回队列
infos = ssh_info_from_file("ssh_info")
thread_pool_size = len(infos)
ssh_infos = ssh_connect(infos)
# 定义执行ssh的多线程 线程数由ssh决定
ssh_thread_pool = threadpool.ThreadPool(thread_pool_size)
while (1 == 1):
# 获取输入
command_str = input("Enter your command : ")
print("Your input command is : ", command_str)
# 方法2
vars = {'sshInfos': ssh_infos, 'command': command_str}
func_vars = [(None, vars)]
requests = threadpool.makeRequests(ssh_exec, func_vars)
for req in requests:
ssh_thread_pool.putRequest(req)
ssh_thread_pool.wait()
打包:
#安装pyinstaller
pip install pyinstaller
#生成打包内容
pyinstaller src\ssh_all.py
#打包为exe文件
pyinstaller -F src\ssh_all.py --hidden-import paramiko
展开阅读全文
版权声明:
本文内容由互联网用户自发贡献,版权归作者所有,本社区不拥有所有权,也不承担相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:jaagool@sina.cn 进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
本文内容由互联网用户自发贡献,版权归作者所有,本社区不拥有所有权,也不承担相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:jaagool@sina.cn 进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。