기계는 거짓말하지 않는다

Python paramiko 프롬프트 상호작용 invoke_shell 본문

Python

Python paramiko 프롬프트 상호작용 invoke_shell

KillinTime 2024. 8. 20. 21:16

Python의 paramiko 모듈을 이용하여 원격 서버에 SSH 접속 후,

passwd와 같이 명령어를 여러 번 주고받아야 할 경우에 간단하게 사용할 수 있는 방법이다.

import paramiko
import time
def instance_change_password(function_args: dict):
'''
args
server_ip, user_name, server_password, new_password
'''
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(function_args['server_ip'], username=function_args['user_name'], password=function_args['server_password'])
# 상호작용 셸 세션
shell = client.invoke_shell()
shell.send('passwd\n')
# 프롬프트 대기
while not shell.recv_ready():
time.sleep(0.5)
output = shell.recv(65535).decode('utf-8')
# 'New password:' 프롬프트를 기다림
if 'New password:' in output:
shell.send(f"{function_args['new_password']}\n")
print("<New Password Entered>")
# 'Retype new password:' 프롬프트를 기다림
while not shell.recv_ready():
time.sleep(0.5)
output = shell.recv(65535).decode('utf-8')
if 'Retype new password:' in output:
shell.send(f"{function_args['new_password']}\n")
print("<Re-entered New Password>")
client.close()
Comments