Paramiko를 사용하여 SSH 반환 코드를 어떻게 얻을 수 있습니까?
client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)
명령 반환 코드를 얻는 방법이 있습니까?
모든 stdout / stderr를 구문 분석하고 명령이 성공적으로 완료되었는지 여부를 아는 것은 어렵습니다.
SSHClient는 Paramiko의 더 낮은 수준의 기능에 대한 간단한 래퍼 클래스입니다. API 문서는 나열 recv_exit_status () 채널 클래스의 방법을.
매우 간단한 데모 스크립트 :
$ cat sshtest.py
import paramiko
import getpass
pw = getpass.getpass()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('127.0.0.1', password=pw)
while True:
cmd = raw_input("Command to run: ")
if cmd == "":
break
chan = client.get_transport().open_session()
print "running '%s'" % cmd
chan.exec_command(cmd)
print "exit status: %s" % chan.recv_exit_status()
client.close()
$ python sshtest.py
Password:
Command to run: true
running 'true'
exit status: 0
Command to run: false
running 'false'
exit status: 1
Command to run:
$
"낮은 수준"채널 클래스를 직접 호출하지 않는 훨씬 더 쉬운 예입니다 (예 : 명령을 사용 하지 않음client.get_transport().open_session()
).
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('blahblah.com')
stdin, stdout, stderr = client.exec_command("uptime")
print stdout.channel.recv_exit_status() # status is 0
stdin, stdout, stderr = client.exec_command("oauwhduawhd")
print stdout.channel.recv_exit_status() # status is 127
JanC 덕분에 예제에 대한 수정 사항을 추가하고 Python3에서 테스트했습니다. 정말 유용했습니다.
import paramiko
import getpass
pw = getpass.getpass()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
#client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def start():
try :
client.connect('127.0.0.1', port=22, username='ubuntu', password=pw)
return True
except Exception as e:
#client.close()
print(e)
return False
while start():
key = True
cmd = input("Command to run: ")
if cmd == "":
break
chan = client.get_transport().open_session()
print("running '%s'" % cmd)
chan.exec_command(cmd)
while key:
if chan.recv_ready():
print("recv:\n%s" % chan.recv(4096).decode('ascii'))
if chan.recv_stderr_ready():
print("error:\n%s" % chan.recv_stderr(4096).decode('ascii'))
if chan.exit_status_ready():
print("exit status: %s" % chan.recv_exit_status())
key = False
client.close()
client.close()
In my case, output buffering was the problem. Because of buffering, the outputs from the application doesn't come out non-blocking way. You can find the answer about how to print output without buffering in here: Disable output buffering. For short, just run python with -u option like this:
> python -u script.py
참고URL : https://stackoverflow.com/questions/3562403/how-can-you-get-the-ssh-return-code-using-paramiko
'development' 카테고리의 다른 글
부모 클래스 (정적 컨텍스트)에서 자식 클래스의 이름 가져 오기 (0) | 2020.09.10 |
---|---|
Python의 임의 해시 (0) | 2020.09.10 |
laravel eloquent에서 특정 열을 선택하는 방법 (0) | 2020.09.10 |
간단한 교착 상태 예 (0) | 2020.09.10 |
(node : 3341) DeprecationWarning : 몽구스 : mpromise (0) | 2020.09.10 |