【问题标题】:How to connect to remote server with paramiko without a password?如何在没有密码的情况下使用 paramiko 连接到远程服务器?
【发布时间】:2019-12-14 05:58:42
【问题描述】:

我正在用 Python 编写一个脚本,它需要使用 SSH 连接到 remote_server 并将 fileremote_server 移动到 host_server。我需要在没有密码的情况下执行此操作,因为它需要适用于任何远程服务器和任何主机服务器用户。

我的代码:

#get IP and username for remote access
IP = input("Enter host_server IP: ").split()
username = input("Enter username: ").split()
#password = ???????

#create a file on host_server for file
file_a = open(date+"file.txt", "a") #ignore the date variable
file = str(date+"file.txt")

#move file to host_server
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP[0], username = user[0], password = password[0])
print "Connected to server."
transfer = ssh.open_sftp()
transfer.get("file.txt", file)
transfer.close()
print "Transfer completed."

问题:有没有办法在脚本中设置公钥而不需要访问命令行终端,这样每次脚本运行时都会使用 SSH 设置无密码访问? p>

【问题讨论】:

    标签: python ssh


    【解决方案1】:

    ssh.connect() 接受关键字参数pkey,您可以使用它来指定您的私人文件。

    #get IP and username for remote access
    IP = input("Enter host_server IP: ").split()
    username = input("Enter username: ").split()
    
    
    #create a file on host_server for file
    file_a = open(date+"file.txt", "a") #ignore the date variable
    file = str(date+"file.txt")
    import paramiko
    import os
    privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
    mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
    ssh.connect(IP[0], username = user[0], pkey = mykey)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多