python - 在 Paramiko 中,从列表或字典中执行命令并将结果保存到列表或字典中
问题描述
在 Paramiko 中,如何将列表或字典传递给列表或字典exec_command
并将结果保存到列表或字典中?
我需要
sleep
在 exec_command 之间。命令不是按顺序执行的,而是按 1、2、1 的顺序执行的。
stdin, stdout, stderr = ssh.exec_command(d.values()[0])
reuslt1 = stdout.read()
stdin, stdout, stderr = ssh.exec_command(d.values()[1])
reuslt2 = stdout.read()
stdin, stdout, stderr = ssh.exec_command(d.values()[0])
reuslt3 = stdout.read()
如果没有上面提到的两个问题,我试过map()
了,效果很好。
cmd = ['xxx', 'xxx']
def func(cmd):
stdin, stdout, stderr= ssh.exec_command(cmd)
result = stdout.read()
return result
list(map(func, cmd))
我的问题是我需要 SSH 远程 Linux,替换文件中的字符串。
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
command = {
"search" : "grep$img_name ='string' file",
"modify" : "sed -i 's/$img_name = $now/$img_name = $word/g' file",
}
stdin, stdout, stderr = ssh.exec_command(command.values()[0])
before = stdout.read()
sleep(1) ##If I don't add the wait, I will grep the string twice before the modification.
ssh.exec_command(command.values()[1])
sleep(1)
stdin, stdout, stderr = ssh.exec_command(command.values()[0])
after = stdout.read() ##Confirm that my modification was successful
ssh.close()
我不想重复编码stdin, stdout, stderr = ssh.exec_command()
。
解决方案
我相信您正在寻找这个:Iterate over dictionaries using 'for' loops。
所以在 Python 3 中:
for key, value in command.items():
stdin, stdout, stderr = ssh.exec_command(value)
results[key] = stdout.read()
关于sleep
:stdout.read()
不仅读取命令输出。作为读取输出的副作用,它等待命令完成。由于您不调用stdout.read()
,因此sed
您不必等待它完成。所以实际上,for
上面的循环也应该解决这个问题,因为它等待所有命令,包括sed
, 完成。
推荐阅读
- amazon-web-services - 如何列出已停止的 AWS RDS 实例
- html - CSS-仅当右侧显示新组件时如何使一个组件向左移动
- python - 可视化 POS 标记文本
- c# - 混合 JWT 和 Windows 身份验证。jwt 失败后弹出凭据
- docker - 无法启动服务 web:OCI 运行时创建失败:container_linux.go:380
- vite - 有没有办法将 Vite 与 HMR 一起使用并且仍然在 /dist 文件夹中生成文件?
- javascript - 循环遍历数组并将图标添加到仅匹配给定 ID
- python - AssertionError at /graphql/ 需要向 GraphQLView 提供 Schema
- c - 如何在 C 中声明指向结构的指针?
- java - 比较两个 Date() 与一天的差异时的一秒差异