【问题标题】:Python how to open and read a remote file after SSH TunnelPython如何在SSH隧道后打开和读取远程文件
【发布时间】:2021-04-12 02:59:54
【问题描述】:

我正在使用 SSHTunnelForwared 并使用以下代码成功进入远程服务器:

with SSHTunnelForwarder((ssh_host, ssh_port), ssh_username=ssh_user,
        ssh_password=ssh_password,
        remote_bind_address=("127.0.0.1", 3306)) as tunnel:

我现在想从服务器内部的路径中将文件读入 python。假设路径是/home/user/file.json

如果我做类似的事情

with open('/home/user/file.json','r') as f:
    data = json.loads(f)

程序抛出错误提示:

FileNotFoundError: [Errno 2] No such file or directory: '/home/user/file.json'

显然找不到该文件。我需要做什么才能找到目录?我在ssh 块内工作,所以我可以访问tunnel 对象。

【问题讨论】:

    标签: python ssh remote-access ssh-tunnel


    【解决方案1】:

    当你连接时你不知道你的默认密码所以尝试访问你的路径然后读取你的文件,希望这对你有帮助

    import paramiko
    
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect("5.206.0.0", username = "root", password = "root")
    command = "cd /var/www/html/ && ls"
    stdin, out, err = client.exec_command(command)
    print "stdout: " + out.read()
    

    也适用于 sql:

    import pymysql
    import paramiko
    import pandas as pd
    from paramiko import SSHClient
    from sshtunnel import SSHTunnelForwarder
    from os.path import expanduser
    
    home = expanduser('~')
    mypkey = paramiko.RSAKey.from_private_key_file(home + pkeyfilepath)
    
    sql_hostname = 'sql_hostname'
    sql_username = 'sql_username'
    sql_password = 'sql_password'
    sql_main_database = 'db_name'
    sql_port = 3306
    ssh_host = 'ssh_hostname'
    ssh_user = 'ssh_username'
    ssh_port = 22
    sql_ip = '1.1.1.1.1'
    
    with SSHTunnelForwarder(
            (ssh_host, ssh_port),
            ssh_username=ssh_user,
            ssh_pkey=mypkey,
            remote_bind_address=(sql_hostname, sql_port)) as tunnel:
        conn = pymysql.connect(host='127.0.0.1', user=sql_username,
                passwd=sql_password, db=sql_main_database,
                port=tunnel.local_bind_port)
        query = '''SELECT VERSION();'''
        data = pd.read_sql_query(query, conn)
        conn.close()
    

    【讨论】:

    • 所以我应该用paramiko.SSHClient 替换SSHTunnelForwarer?因为我已经在带有该模块的服务器中。
    • 是的,我建议,试一试,我认为它会解决你的问题
    • 这可行,但我也使用 sshtunnelForwarder 远程连接到 mysql 服务器,我无法使用 paramiko.sshclient 进行此操作
    • 我更新答案重新检查你的问题
    • 是的,这正是我使用 mysql 的方式,但我想要一种 ssh 隧道的组合方式,并且能够从远程服务器获取文件。你认为我可以结合上述方法吗?即在 sshTunnelForwarder 块中有 sshclient?
    猜你喜欢
    • 2011-05-20
    • 2021-09-24
    • 2016-01-15
    • 2021-05-11
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2023-01-25
    相关资源
    最近更新 更多