如何在 python3 中使用无密码身份验证在 REMOTE 机器中使用子进程方法 运行 命令?
How to run commands in REMOTE machine with the subprocess approach using passwordless authentication in python3?
我正在尝试编写一个脚本,该脚本应该在启用 ssh 的远程计算机中执行一些命令(由 Payload 定义)。我想要无密码连接。这样我就可以使用public和私钥认证了。我知道如何在 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)
您应该使用 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()
我正在尝试编写一个脚本,该脚本应该在启用 ssh 的远程计算机中执行一些命令(由 Payload 定义)。我想要无密码连接。这样我就可以使用public和私钥认证了。我知道如何在 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)
您应该使用 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()