我正在尝试编写一个脚本,该脚本应该在ssh enable远程计算机中执行一些命令(由Payload定义)。我希望有一个passworless连接。这样我就可以使用公钥和私钥验证。我知道如何在paramiko和它的工作中做到这一点。有没有办法通过子进程来获取输出?有没有示例代码?
我的示例代码是这样的。例如,我想稍后执行更多连接。
import subprocess
def __init__ (type, options):
if type=="ssh":
ssh(options)
else if type="fsexec":
fsexec(options)
def ssh(self, ip, user, sshkey_file, payload):
try:
command = "ssh "
prog = subprocess.call(["ssh -i sshkey_file -t user@ip 'payload'"])
print(prog)
print("Returncode:", prog)
def fsexec(self, ip, user, sshkey_file, payload):
try:
command = "ssh "
prog = subprocess.call(["fsexec -t user@ip 'payload'"])
print(prog)
print("Returncode:", prog)
答案 0 :(得分:1)
您应该使用Paramiko库使用ssh和密钥文件登录。
我从一个要点(https://gist.github.com/batok/2352501)复制了一个例子:
import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.acme.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "/home/ubuntu/firstscript.sh", "/home/ubuntu/secondscript.sh" ]
for command in commands:
print "Executing {}".format( command )
stdin , stdout, stderr = c.exec_command(command)
print stdout.read()
print( "Errors")
print stderr.read()
c.close()