python - Paramiko parallel execution to the remote unix hosts
问题描述
I have a below script which i'm using to execute commands on remote hosts as a cetralized user, but this script is reads the host file and execute the command one by one however it also remains on the session until its not unlinked from the shell, Hence i want to have a parallel execution saying that when running the script it should be able to fork multiple ssh connection and login to the host and exit immeadiaely after command execution.
Please let me know if you guys have any trick or expert inputs. Though i'm using paramiko as these hosta rae legarcy UNIX hosts where i'm unable to use ansible or like utilities due to some restrictions.
import paramiko
with open('/data/CR9432/SunOS.txt', 'r') as f:
for host in f:
remote_host = host.rstrip()
remote_pass = "pass123"
smart_user = "mtrooper"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_host, username=smart_user, password=remote_pass)
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
#for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
############################################
#session.exec_command("shutdown -y -i5 -g0")
############################################
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
#you have to check if you really need to send password here
stdin.write(remote_pass +'\n')
stdin.flush()
print"\n"
print "------------------------------------------------------------------------------"
print "Command Execution Output On Hostname: "
print "------------------------------------------------------------------------------"
for line in stdout.read().splitlines():
print 'host: %s: %s' % (remote_host, line)
解决方案
推荐阅读
- php - 无法将数据插入表中。邮政不工作?
- python - Python Youtube Api 开发者密钥
- cuda - 使用 numba cuda 注册数组
- laravel - Laravel 基于数据库值的条件路由
- hyperledger-fabric - Hyperledger Fabric:检查交易是否已提交到账本
- mongodb - Mongo聚合嵌套数组,查找
- python - 尝试从 Python 中的多个 .txt 文件中读取数组,但没有出现任何内容
- python - 使用“另存为”下载的 HTML 与使用 Python 请求下载的 HTML 略有不同
- sql-server - 对多个服务器的 SQL 查询失败
- java - Selenium + 代理 = 失败