使用 python SSH 和 telnet 到本地主机 [英] SSH and telnet to localhost using python

查看:59
本文介绍了使用 python SSH 和 telnet 到本地主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,如果问题很笨拙,我深表歉意.简单地说,我需要编写一个脚本,通过 ssh 连接到远程,然后 telnets 到 localhost 并在那里的 shell 上执行命令.

I am new to python and if the question is very nooby i apologize. Simply put i need to write a script that connects to remote via ssh then telnets to localhost and execute a command on a shell there.

我使用的是 Python 2.4.3.我在这里阅读了很多类似的问题,很多人建议使用 Paramiko、Pexpect 等模块.但是这是不可能的 - 我应该只使用本机"2.4.3 库.我试过弄乱子进程模块,我已经设法连接到远程 shell(但是我需要提供密码 - 我想通过在脚本中提供密码来避免这种情况) - 但我仍然需要做一个telnet 到 localhost 并在不同的 shell 上执行几个命令.

I am using Python 2.4.3. I have read alot of similar questions here , and alot of people suggest to use modules such as Paramiko, Pexpect etc. However this is out of question - i am supposed to use only "native" 2.4.3 libraries. I have tried messing around with subprocess module and i have managed to connect to remote shell (however i need to provide a password - and i would like to avoid that by providing a password in script for example) - but still i need to do a telnet to localhost and execute few commands on a different shell.

有人能这么好心给我一些提示吗?提前致谢.

Could someone be so kind and give me some hints? Thanks in advance.

TL;DR 我正在寻找这个 bash 命令的 python 替代方案:

TL;DR I am looking for python alternative to this bash command :

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

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

推荐答案

经过简单的搜索:

远程登录:链接

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:链接

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)

这篇关于使用 python SSH 和 telnet 到本地主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆