使用 python SSH 和 telnet 到本地主机

SSH and telnet to localhost using python

我是 python 的新手,如果这个问题很笨,我深表歉意。简单地说,我需要编写一个脚本,通过 ssh 连接到远程,然后远程登录到本地主机,并在 shell 上执行命令。

我正在使用 Python 2.4.3。我在这里阅读了很多类似的问题,很多人建议使用 Paramiko、Pexpect 等模块。但是这是不可能的——我应该只使用 "native" 2.4.3 库。我试过弄乱 subprocess 模块,我已经设法连接到远程 shell (但是我需要提供密码 - 我想通过在脚本中提供密码来避免这种情况) - 但我仍然需要远程登录到本地主机并在不同的 shell.

上执行一些命令

有好心人给我点提示吗?提前致谢。

TL;DR 我正在寻找 python 替代此 bash 命令的方法:

./sshpass -p password ssh username@$ip -t "(sleep 1;echo "command" ; sleep 1) | telnet localhost $port;exit;bash" >> testing.txt

简单搜索后:

telnet: link

import getpass
import sys
import telnetlib

HOST = "hostname"

user = raw_input("Enter your remote account: ")

password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")

tn.write(user + "\n")

if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")

tn.write("exit\n")

print tn.read_all()

ssh: link

import pxssh
import getpass
try:                                                            
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login (hostname, username, password)
    s.sendline ('uptime')   # run a command
    s.prompt()             # match the prompt
    print s.before          # print everything before the prompt.
    s.sendline ('ls -l')
    s.prompt()
    print s.before
    s.sendline ('df')
    s.prompt()
    print s.before
    s.logout()
except pxssh.ExceptionPxssh, e:
    print "pxssh failed on login."
    print str(e)