[英]Perform commands over ssh with Python
我正在编写一个脚本来自动化 Python 中的一些命令行命令。 目前,我正在做这样的电话:
cmd = "some unix command"
retcode = subprocess.call(cmd,shell=True)
但是,我需要在远程机器上运行一些命令。 手动,我将使用ssh
登录,然后运行命令。 我将如何在 Python 中自动执行此操作? 我需要使用(已知)密码登录远程机器,所以我不能只使用cmd = ssh user@remotehost
,我想知道是否有我应该使用的模块?
看到这个问题
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)
如果您使用 ssh 密钥,请执行以下操作:
k = paramiko.RSAKey.from_private_key_file(keyfilename)
# OR k = paramiko.DSSKey.from_private_key_file(keyfilename)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, pkey=k)
或者你可以只使用commands.getstatusoutput :
commands.getstatusoutput("ssh machine 1 'your script'")
我广泛使用它,效果很好。
在Python 2.6+,使用subprocess.check_output
。
把事情简单化。 不需要库。
import subprocess
subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
你看过Fabric吗? 它允许您使用python通过SSH执行各种远程操作。
我发现 paramiko 有点太低级了,而且 Fabric 不太适合用作库,所以我把我自己的库放在一起,叫做spur ,它使用 paramiko 来实现一个稍微好一点的界面:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
如果您需要在 shell 中运行:
shell.run(["sh", "-c", "echo -n hello"])
所有人都已经声明(推荐)使用paramiko ,我只是分享了一个 python 代码(有人可能会说 API),它可以让你一次性执行多个命令。
在不同的节点上执行命令使用: Commands().run_cmd(host_ip, list_of_commands)
你会看到一个 TODO,如果有任何命令执行失败,我会一直停止执行,我不知道该怎么做。 请分享您的知识
#!/usr/bin/python
import os
import sys
import select
import paramiko
import time
class Commands:
def __init__(self, retry_time=0):
self.retry_time = retry_time
pass
def run_cmd(self, host_ip, cmd_list):
i = 0
while True:
# print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time))
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host_ip)
break
except paramiko.AuthenticationException:
print("Authentication failed when connecting to %s" % host_ip)
sys.exit(1)
except:
print("Could not SSH to %s, waiting for it to start" % host_ip)
i += 1
time.sleep(2)
# If we could not connect within time limit
if i >= self.retry_time:
print("Could not connect to %s. Giving up" % host_ip)
sys.exit(1)
# After connection is successful
# Send the command
for command in cmd_list:
# print command
print "> " + command
# execute commands
stdin, stdout, stderr = ssh.exec_command(command)
# TODO() : if an error is thrown, stop further rules and revert back changes
# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0)
if len(rl) > 0:
tmp = stdout.channel.recv(1024)
output = tmp.decode()
print output
# Close SSH connection
ssh.close()
return
def main(args=None):
if args is None:
print "arguments expected"
else:
# args = {'<ip_address>', <list_of_commands>}
mytest = Commands()
mytest.run_cmd(host_ip=args[0], cmd_list=args[1])
return
if __name__ == "__main__":
main(sys.argv[1:])
谢谢!
添加额外的行后, paramiko终于为我工作了,这真的很重要(第 3 行):
import paramiko
p = paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # This script doesn't work for me unless this line is added!
p.connect("server", port=22, username="username", password="password")
stdin, stdout, stderr = p.exec_command("your command")
opt = stdout.readlines()
opt = "".join(opt)
print(opt)
确保已安装 paramiko 包。 解决方案的原始来源: Source
接受的答案对我不起作用,这是我使用的:
import paramiko
import os
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh.load_system_host_keys()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.connect("d.d.d.d", username="user", password="pass", port=22222)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("ls -alrt")
exit_code = ssh_stdout.channel.recv_exit_status() # handles async exit error
for line in ssh_stdout:
print(line.strip())
total 44
-rw-r--r--. 1 root root 129 Dec 28 2013 .tcshrc
-rw-r--r--. 1 root root 100 Dec 28 2013 .cshrc
-rw-r--r--. 1 root root 176 Dec 28 2013 .bashrc
...
或者,您可以使用sshpass :
import subprocess
cmd = """ sshpass -p "myPas$" ssh user@d.d.d.d -p 22222 'my command; exit' """
print( subprocess.getoutput(cmd) )
参考:
笔记:
ssh root@ip
) 手动连接到远程系统并接受公钥,这是很多时候无法使用paramiko
或其他自动ssh
脚本进行连接的原因。import paramiko
import time
ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
print('connected')
stdin, stdout, stderr = ssh.exec_command(" ")
def execute():
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
execute()
您可以使用这些命令中的任何一个,这也将帮助您提供密码。
cmd = subprocess.run(["sshpass -p 'password' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@domain.com ps | grep minicom"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(cmd.stdout)
OR
cmd = subprocess.getoutput("sshpass -p 'password' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@domain.com ps | grep minicom")
print(cmd)
看一下spurplus
,这是我们围绕spur
开发的包装器,它提供类型注释和一些小技巧(重新连接SFTP、md5等): https : //pypi.org/project/spurplus/
#Reading the Host,username,password,port from excel file
import paramiko
import xlrd
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0,1)
Port = int(sheet.cell_value(3,1))
User = sheet.cell_value(1,1)
Pass = sheet.cell_value(2,1)
def details(Host,Port,User,Pass):
ssh.connect(Host, Port, User, Pass)
print('connected to ip ',Host)
stdin, stdout, stderr = ssh.exec_command("")
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
details(Host,Port,User,Pass)
要求用户根据他们登录的设备输入命令。
以下代码由 PEP8online.com 验证。
import paramiko
import xlrd
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0, 1)
Port = int(sheet.cell_value(3, 1))
User = sheet.cell_value(1, 1)
Pass = sheet.cell_value(2, 1)
def details(Host, Port, User, Pass):
time.sleep(2)
ssh.connect(Host, Port, User, Pass)
print('connected to ip ', Host)
stdin, stdout, stderr = ssh.exec_command("")
x = input('Enter the command:')
stdin.write(x)
stdin.write('\n')
print('success')
details(Host, Port, User, Pass)
第一:我很惊讶还没有人提到fabric
。
第二:对于您描述的那些要求,我已经实现了一个名为jk_simpleexec
的自己的python 模块。 它的目的是:使运行命令变得容易。
让我为你解释一下。
我的 python 模块jk_simpleexec
提供了一个名为runCmd(..)
的函数,它可以在本地或远程执行 shell (!) 命令。 这很简单。 以下是本地执行命令的示例:
import jk_simpleexec
cmdResult = jk_simpleexec.runCmd(None, "cd / ; ls -la")
注意:请注意,默认情况下会自动修剪返回的数据,以从 STDOUT 和 STDERR 中删除过多的空行。 (当然,可以停用此行为,但出于您的目的,您要牢记该行为正是您想要的。)
您将收到一个包含返回代码、STDOUT 和 STDERR 的对象。 因此,处理结果非常容易。
这就是您想要做的,因为您执行的命令可能存在并已启动,但可能无法执行预期的操作。 在您对 STDOUT 和 STDERR 不感兴趣的最简单情况下,您的代码可能如下所示:
cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)
出于调试目的,您希望在某个时间将结果输出到 STDOUT,因此您可以这样做:
cmdResult.dump()
如果您想处理 STDOUT,它也很简单。 例子:
for line in cmdResult.stdOutLines:
print(line)
现在当然我们可能想在另一个系统上远程执行这个命令。 为此,我们可以以完全相同的方式使用相同的函数runCmd(..)
,但我们需要先指定一个fabric
连接对象。 这可以像这样完成:
from fabric import Connection
REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = "mypwd"
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})
cmdResult = jk_simpleexec.runCmd(c, "cd / ; ls -la")
# ... process the result stored in cmdResult ...
c.close()
一切都保持完全相同,但这次我们在另一台主机上运行此命令。 这是为了:我想要一个统一的 API,如果您在某个时候决定从本地主机移动到另一台主机,则不需要对软件进行修改。
现在当然有密码问题。 上面已经有一些用户提到了这一点:我们可能想要求执行此 python 代码的用户输入密码。
对于这个问题,我很久以前就创建了一个自己的模块。 jk_pwdinput
。 与常规密码输入的不同之处在于jk_pwdinput
将输出一些星星而不是只打印任何内容。 因此,对于您输入的每个密码字符,您都会看到一个星号。 这样,您输入密码就更容易了。
这是代码:
import jk_pwdinput
# ... define other 'constants' such as REMOTE_LOGIN, REMOTE_HOST ...
REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")
(为了完整readpwd(..)
:如果readpwd(..)
返回None
则用户使用 Ctrl+C 取消密码输入。在现实世界中,您可能希望对此采取适当的行动。)
这是一个完整的例子:
import jk_simpleexec
import jk_pwdinput
from fabric import Connection
REMOTE_HOST = "myhost"
REMOTE_PORT = 22
REMOTE_LOGIN = "mylogin"
REMOTE_PASSWORD = jk_pwdinput.readpwd("Password for " + REMOTE_LOGIN + "@" + REMOTE_HOST + ": ")
c = Connection(host=REMOTE_HOST, user=REMOTE_LOGIN, port=REMOTE_PORT, connect_kwargs={"password": REMOTE_PASSWORD})
cmdResult = jk_simpleexec.runCmd(
c = c,
command = "cd / ; ls -la"
)
cmdResult.raiseExceptionOnError("Something went wrong!", bDumpStatusOnError=True)
c.close()
所以我们有全套:
上面的代码对我来说很好地解决了这个问题(希望对你也是如此)。 一切都是开源的:Fabric 是BSD-2-Clause ,我自己的模块在Apache-2下提供。
使用的模块:
快乐编码! ;-)
最现代的方法可能是使用fabric 。 此模块允许您设置 SSH 连接,然后运行命令并通过连接对象获取结果。
这是一个简单的例子:
from fabric import Connection
with Connection("your_hostname") as connection:
result = connection.run("uname -s", hide=True)
msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
print(msg.format(result))
我编写了一个简单的 class 来通过本地 ssh 远程运行命令,使用subprocess
进程模块:
from ssh_utils import SshClient
client = SshClient(user='username', remote='remote_host', key='path/to/key.pem')
# run a list of commands
client.cmd(['mkdir ~/testdir', 'ls -la', 'echo done!'])
# copy files/dirs
client.scp('my_file.txt', '~/testdir')
https://gist.github.com/mamaj/a7b378a5c969e3e32a9e4f9bceb0c5eb
import subprocess
from pathlib import Path
from typing import Union
class SshClient():
""" Perform commands and copy files on ssh using subprocess
and native ssh client (OpenSSH).
"""
def __init__(self,
user: str,
remote: str,
key_path: Union[str, Path]) -> None:
"""
Args:
user (str): username for the remote
remote (str): remote host IP/DNS
key_path (str or pathlib.Path): path to .pem file
"""
self.user = user
self.remote = remote
self.key_path = str(key_path)
def cmd(self,
cmds: list[str],
strict_host_key_checking=False) -> None:
"""runs commands consecutively, ensuring success of each
after calling the next command.
Args:
cmds (list[str]): list of commands to run.
strict_host_key_checking (bool, optional): Defaults to True.
"""
strict_host_key_checking = 'yes' if strict_host_key_checking \
else 'no'
cmd = ' && '.join(cmds)
subprocess.run(
[
'ssh',
'-i', self.key_path,
'-o', f'StrictHostKeyChecking={strict_host_key_checking}',
'-o', 'UserKnownHostsFile=/dev/null',
f'{self.user}@{self.remote}',
cmd
]
)
def scp(self, source: Union[str, Path], destination: Union[str, Path]):
"""Copies `srouce` file to remote `destination` using the
native `scp` command.
Args:
source (Union[str, Path]): Source file path.
destination (Union[str, Path]): Destination path on remote.
"""
subprocess.run(
[
'scp',
'-i', self.key_path,
str(source),
f'{self.user}@{self.remote}:{str(destination)}',
]
)
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def details():
Host = input("Enter the Hostname: ")
Port = input("Enter the Port: ")
User = input("Enter the Username: ")
Pass = input("Enter the Password: ")
ssh.connect(Host, Port, User, Pass, timeout=2)
print('connected')
stdin, stdout, stderr = ssh.exec_command("")
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
details()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.