2019년 2월 22일 금요일

[Python] SSH, SFTP Example


1. SSH, SFTP Library

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import paramiko

def sshCommand(host,user,passwd,command):
    ssh = paramiko.SSHClient()
    #ssh.load_system_host_keys(filename='/home/barashe/.ssh/known_hosts')
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=user, password=passwd)
    return ssh.exec_command(command) #in, out, err
    
class pyssh():
    def __init__(self,host,user,passwd):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(host, username=user, password=passwd)
        self.passwd = passwd

    def close(self):
        self.ssh.close()
        
    def execute(self,cmd):
        return self.ssh.exec_command(cmd) #in, out, err
    
    def sudo_execute(self,cmd):
        stdin, stdout, stderr = self.ssh.exec_command('sudo ' + cmd)
        stdin.write( self.passwd.encode('utf-8') + b'\n')
        stdin.flush()
        return stdin, stdout, stderr
    
class pysftp():    
    def __init__(self,host,user,passwd):
        self.trans = paramiko.Transport((host,22))
        self.trans.connect(username=user,password=passwd)
        self.sftp = paramiko.SFTPClient.from_transport(self.trans) 

    def put(self,local,remote):
        return self.sftp.put(local,remote)

    def get(self,remote,local):
        return self.sftp.get(remote,local)


2. SSH, SFTP Library Test Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def sshTest():
    ssh = pyssh(sys.argv[1],sys.argv[2],sys.argv[3])
    ins, outs, errs = ssh.execute("ls -l")
    while True:
        data = outs.read(10)
        if not data:
            break;
        print( data );
    ins, outs, errs = ssh.execute("pwd")
    print( outs.read() );
    
def sftpTest():
    sftp = pysftp(sys.argv[1],sys.argv[2],sys.argv[3])
    rv = sftp.put("D:/temp/line.png", "line.png")
    print(rv)
    rv = sftp.get("line.png", "D:/temp/line_200.png")
    print(rv)


댓글 없음:

댓글 쓰기