我能够运行一个脚本但是当我尝试从另一个模块调用其中的函数(在其他文件中调用函数)时,我得到一个未定义的全局名称错误。
>>> reachable('192.168.1.200','192.168.1.1','test','password')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "reachable.py", line 5, in reachable
s1=reachableFrom.start_session(host1,user,pw,user,pw,'ssh')
File "reachableFrom.py", line 21, in start_session
NameError: global name 'Secure_Shell' is not defined
# reachable.py
import Telnet, Session, Secure_Shell, re
from reachableFrom import start_session,send_commands_to_session
def reachable(host1,host2,user,pw):
s1=reachableFrom.start_session(host1,user,pw,user,pw,'ssh')
command='ping '+host2+' count 5'
(success,results)=reachableFrom.send_commands_to_session(s1,command,conf_mode=False)
out=re.compile(r'.* (\d*) percent .*',re.MULTILINE)
m=out.match(str(results))
return(m.group(1))
当我从命令行运行reachableFrom.py时,start_session函数正常工作。
#reachableFrom.py
import Session
import re
import Telnet
import Secure_Shell
import sys
method='ssh'
host1='192.168.1.200'
host2='192.168.1.1'
user='test'
pw='password'
def start_session(device, username, password, enable_username, enable_password, via):
session1 = None
if via == 'telnet':
session1 = Telnet.Telnet(device, username, password, enable_username, enable_password)
if via == 'ssh':
session1 = Secure_Shell.Secure_Shell(device, username, password,enable_username, enable_password)
return session1
def send_commands_to_session(session, command, conf_mode=False):
''' sends a series of cli lines to a device (seperated by ';') '''
output = []
# if command list comes in seperated by newline, replace with ';'
command = command.replace('\n', ';')
# split command list into individual lines
commands = command.split(';')
if session.login():
if session.enter_enable_mode():
session.page_skip()
for line in commands:
output=session.send_line(line)
return (True, output)
return (False, {})
s1=start_session(host1,user,pw,user,pw,method)
command='ping '+host2+' count 5'
(success,results)=send_commands_to_session(s1,command,conf_mode=False)
out=re.compile(r'.* (\d*) percent .*',re.MULTILINE)
m=out.match(str(results))
print(m.group(1))
rick@ST2:~/python$ python reachableFrom.py
100
所以我想弄清楚为什么从reachableFrom.py调用Secure_Shell但是从reachable.reachable启动时没有。我认为这可能是我对解释器,命名空间或继承的理解的问题。谢谢!