如何使用exscriptframework自动登录ssh服务器?

2024-06-24 12:46:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要登录到SSH服务器并在同一个会话上执行多个“ROS”命令。我寻找了一个在第一个命令后保持连接的框架,唯一做得好的是Exscript框架。我的代码很简单,我从一个XML文件中选择用户名、端口、客户机和地址,并使用该凭据登录。但是当我使用Account类进行自动登录(没有提示输入用户和密码)时,我总是收到错误连接被拒绝最终关闭。但是,如果我运行代码时没有尝试自动登录,与入门代码类似,并且从XML到login的值相同,则一切正常。有人能帮忙吗

Obs:已经尝试了this thread中的代码,但是这些代码都不起作用(即使没有使用XML)

# -*- coding: utf-8 -*-
from Exscript.util.start import start
from Exscript.util.interact import read_login
from Exscript import Host, Account
import Exscript
from Exscript.protocols import SSH2
try:
    import xml.etree.cElementTree as et
except ImportError:
    import xml.etree.ElementTree as et

# Reads the XML File
xmlFile = et.parse('environment.xml')
# Find the root element from the file (in this case "environment")
root = xmlFile.getroot()


address = root.findtext('TURTLEBOT_IP')
usernameClient = root.findtext('USERNAME')
passwordClient = root.findtext('PASSWORD')
portClient = root.findtext('PORT')

myIP = root.findtext('MY_IP')
masterIP = root.findtext('MASTER_IP')
rosMasterURI = root.findtext('ROS_MASTER_URI')
rosHostname = root.findtext('ROS_HOSTNAME')
rosNamespace = root.findtext('ROS_NAMESPACE')
address = root.findtext('TURTLEBOT_IP')
usernameClient = root.findtext('USERNAME')
passwordClient = root.findtext('PASSWORD')
portClient = root.findtext('PORT')
perspectiveLocation = root.findtext('PERSPECTIVE_LOCATION')
rosSource = root.findtext("ROS_SOURCE")
rosEtc = root.findtext('ROS_ETC_DIRECTORY')
rosRoot = root.findtext('ROS_ROOT')

exportIP = str('ROS_IP='+myIP)
exportMasterIP = str('MASTER_IP='+myIP)
exportMasterIPURI = str('export ROS_MASTER_URI=http://$MASTER_IP:11311/')
exportRosIP = str('export ROS_IP=$MY_IP')
exportHostname = str('export ROS_HOSTNAME_IP=$MY_IP')
exportNamespace = str('export ROS_NAMESPACE='+rosNamespace)
print(exportMasterIP)
print(exportRosIP)
print(exportHostname)
print(exportNamespace)
# print(address)

accountLogin = [Account(usernameClient, passwordClient)]
conn = SSH2()
host1 = Host(address)
host1.set_account(accountLogin)
conn.connect(address)


def cmd(job, host, conn):
    conn.execute(str(exportIP+'\n'+exportMasterIP+'\n'+exportMasterIPURI+'\n'+
                     exportRosIP+'\n'+exportHostname+'\n'+exportNamespace))
    conn.execute('roscore')
    conn.execute('roslaunch turtlebot_bringup minimal.launch')
    conn.execute('roslaunch turtlebot_teleop keyboard_teleop.launch')
    conn.execute()


start(accountLogin, host1, cmd, max_threads=2)

# conn.send('quit\r')
# conn.close()

Tags: 代码fromimportipmasterexecuteaddressros