paramiko 모듈을 이용하여 원격 리눅스 서버에 SSH 접속


pip를 이용하여 paramiko 모듈 설치


1
python -m pip install paramiko
cs


paramiko ssh 기본 접속 설정


1
2
3
4
5
6
7
8
9
10
11
import paramiko
import time
 
def main():
    HOST = 'ip_address'
 
    try:
        ssh = paramiko.SSHClient()
        # SSH Host key 설정
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username='USERNAME', password='PW')
cs


기본적으로 한번 connect 된 상태에서 명령어를 실행할 때 마다 하나의 채널이 생성되고 종료되는 것이 반복된다.

su 커맨드를 사용하기 위해서는 채널을 유지시켜 줘야 하는데, 이 때 invoke_shell()를 사용하면 된다.


1
2
3
4
channel = ssh.invoke_shell()
 
channel.send('su -\n')
channel.send('password\n')
cs



전체 코드


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
40
41
import paramiko
import time
 
def main():
    HOST = 'ip_address'
 
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username='USERNAME', password='PW')
        channel = ssh.invoke_shell()
 
        channel.send('su -\n')
        outdata, errdata = waitStreams(channel)
        print (outdata)
        channel.send('PW2\n')
        outdata, errdata = waitStreams(channel)
        print (outdata)
 
        channel.send('touch python_test_is_complete\n')
        outdata, errdata = waitStreams(channel)
        print (outdata)
 
    finally:
        if ssh is not None:
            ssh.close()
 
# python 모듈을 실행하는 커맨드 라인에서 출력 결과를 보여는 
def waitStreams(chan):
    time.sleep(1)
    outdata=errdata = ""
 
    while chan.recv_ready():
        outdata += str(chan.recv(1000))
    while chan.recv_stderr_ready():
        errdata += str(chan.recv_stderr(1000))
 
    return outdata, errdata
 
if __name__ == "__main__":
    main()
cs



Python 3.7.2 Traceback


1
TypeError: can only concatenate str (not "bytes") to str
cs


전체코드 33 ~ 36: byte로 읽은 데이터를 str 타입으로 변환 시켜 저장해야 정상적으로 print를 사용할 수 있다.

'Python' 카테고리의 다른 글

Python pip local package install  (0) 2023.06.21
pipsi - pip script installer  (1) 2019.06.04
flask: download file from directory  (0) 2019.01.02
Flask on apache via mod_wsgi  (0) 2018.12.06
Python 2.6 to 2.7 (or 3.x)  (0) 2018.11.23

+ Recent posts