LoginSignup
18
14

More than 5 years have passed since last update.

Pythonでssh_configのProxyCommand使ってssh接続メモ

Posted at

ssh_configに以下のような設定で、fumidai_host経由でapp_hostにssh接続する構成で、paramiko使ってssh接続する場合のメモ

Host fumidai_host
    User user_name
    Hostname xx.xx.xx.xx (<= GIP)
    IdentityFile ~/.ssh/hoge.pem


Host app_host
    HostName 192.168.0.1 (<= private ip)
    User user_name
    IdentityFile ~/.ssh/hoge.pem
    ProxyCommand ssh -W %h:%p fumidai_host

こんな感じで接続できます。とりあえずsftpするsample


import os
import paramiko


# ssh config fileを lookup
config_file = os.path.join(os.getenv('HOME'), '.ssh/config')
ssh_config = paramiko.SSHConfig()
ssh_config.parse(open(config_file, 'r'))
lkup = ssh_config.lookup(hostname)

# ProxyCommandの設定使って接続
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(
    lkup['hostname'],
    username=lkup['user'],
    key_filename=lkup['identityfile'],
    sock=paramiko.ProxyCommand(lkup['proxycommand'])
)


sftp = ssh.open_sftp()        
# あとは普通に
# sftp.put(src, dist)したり
# sftp.get(src, dist)したり

sftp.close()
ssh.close()

18
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
14