Edited at

SFTPのファイルオブジェクトを取得する (Perl/Ruby/Python)

URL

基本
https://qiita.com/cielavenir/items/9d068c49186060a47650

Pythonの.ssh/config読み出し
https://qiita.com/cielavenir/items/6aa9e6dc1166ae947c6f

大きいファイルの取得
https://qiita.com/cielavenir/items/f38223c156e4aaab58ad


  • Getting file object on SFTP.

  • The situation to get my authorized_keys is arbitrary.


Perl


sftp_file.pl

#!/usr/bin/perl

use strict;
use Net::SFTP::Foreign;
my $sftp = Net::SFTP::Foreign->new('localhost'); #,user=>$ENV{'USER'});
my $fh = $sftp->open('.ssh/authorized_keys',Net::SFTP::Foreign::Constants::SSH2_FXF_READ);
my $file_content;
for(<$fh>){$file_content.=$_;}
$fh->close;
print $file_content;
$sftp->disconnect;


Ruby


sftp_file.rb

#!/usr/bin/ruby

require 'net/sftp'
Net::SFTP.start('localhost',nil){|sftp| # ENV['USER']
sftp.file.open('.ssh/authorized_keys','r'){|file|
puts file.read
}
}


Python

configで凝ったことをしている場合は https://qiita.com/cielavenir/items/6aa9e6dc1166ae947c6f が必要です


sftp_file.py

#!/usr/bin/python

#Py2/Py3 are supported
import os,sys
import paramiko
with paramiko.SSHClient() as ssh:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost') #,username=os.environ['USER'])
with ssh.open_sftp() as sftp:
with sftp.file('.ssh/authorized_keys','r') as f:
sys.stdout.write(f.read().decode('utf-8'))