[英]Python + SSH Password auth (no external libraries or public/private keys)?
所以我知道你可以使用Pexpect
來解決這個問題,但我不想依賴額外的庫來解決除Python3提供的問題之外的問題。
我也知道生成公鑰並允許它們在遠程主機上是理想的,但這就是我打算使用這個腳本(在正確的位置設置鍵等)。
這是因為我在SO社區的幫助下獲得了“我自己的”。 如果分叉的子偽終端完成了它應該執行的操作,我會陷入困境。 這意味着我可以判斷SSH是否已完成執行,因為只要run()
函數正在運行,它就會繼續run()
。
(我的pid_exists
將在run()操作中返回True
。如果我快速退出run()
,SSH會話將沒有足夠的時間來執行它應該做的事情)
#!/usr/bin/python
import pty, sys
from subprocess import Popen, PIPE, STDOUT
from time import sleep
from os.path import expanduser, abspath
from os import walk, setsid, fork, waitpid, execv, read, write, kill
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid < 0:
return False
try:
kill(pid, 0)
except (OSError, e):
return e.errno == errno.EPERMRM
else:
return True
class ssh():
def __init__(self, host, execute='echo "done" > /root/testing.txt', user='root', password=b'SuperPassword'):
self.exec = execute
self.host = host
self.user = user
self.password = password
self.run()
def run(self):
command = [
'/usr/bin/ssh',
self.user+'@'+self.host,
'-o', 'NumberOfPasswordPrompts=1',
self.exec,
]
# PID = 0 for child, and the PID of the child for the parent
pid, child_fd = pty.fork()
if not pid: # Child process
# Replace child process with our SSH process
execv(command[0], command)
while True:
output = read(child_fd, 1024).strip()
print(output)
lower = output.lower()
# Write the password
if b'password:' in lower:
write(child_fd, self.password + b'\n')
break
elif 'are you sure you want to continue connecting' in lower:
# Adding key to known_hosts
write(child_fd, b'yes\n')
elif 'company privacy warning' in lower:
pass # This is an understood message
else:
print('Error:',output)
sleep(5)
print(pid_exists(pid))
ssh('10.10.10.1')
我找不到很多(或任何)有關如何獲取Python打開和管道的偽偽終端的執行過程的信息。 我可以或者我應該如下所述涉及子流程: https : //stackoverflow.com/a/12235442/929999還是有其他方法嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.