LoginSignup
21
26

More than 5 years have passed since last update.

【Ruby】SSH接続してコマンド実行&SCPでファイル転送

Last updated at Posted at 2016-06-11

なにこれ

最近、Python→Rubyに移行していこうと思っていて、その中で学んだ事です。
Rubyで指定した鍵(と鍵のパスワード)を使って、サーバーにSSH接続しコマンド実行、コマンド実行後にファイル転送をするという内容です。

インフラやってる人に特に役に立つかも。

準備

gem install net-ssh
gem install net-scp

想定環境

  • 接続先: 172.17.0.2
  • 鍵Path: /home/user/.ssh/this_is_private_key.key
  • 鍵Password: tomori_nao

Code

  opt = {
    :keys => '/home/user/.ssh/this_is_private_key.key',
    :passphrase => 'tomori_nao',
    :port => 22
  }
  Net::SSH.start('172.17.0.2', '<USERNAME>', opt) do |ssh|
    cmd1 = 'echo tomori > nao.txt'
    ssh.exec!(cmd1)
    # File Transfer over SSH
    src_path = '/home/<USERNAME>/nao.txt'
    dst_path = './nao.txt'
    ssh.scp.download! src_path, dst_path
  end

まとめ

はい、できました。めでたしめでたし♥

21
26
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
21
26