簡體   English   中英

如何使用python3中的無密碼身份驗證通過子進程方法在REMOTE機器中運行命令?

[英]How to run commands in REMOTE machine with the subprocess approach using passwordless authentication in python3?

我正在嘗試編寫一個腳本,該腳本應在ssh enable遠程計算機中執行一些命令(由Payload定義)。 我想建立一個無密碼的連接。 這樣我就可以使用公鑰和私鑰身份驗證。 我知道如何在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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM