简体   繁体   English

Python Netmiko 获取主机名

[英]Python Netmiko to get hostname

I was able to get device hostname with the following netmiko code.我能够使用以下 netmiko 代码获取设备主机名。

>>> print(net_connect.find_prompt())
Cisco#
>>> 

>>> print(net_connect.send_command('show running-config | include hostname'))
hostname Cisco
>>> 

Would it be possible to remove # and hostname from the output?是否可以从 output 中删除#hostname

Desired Output所需 Output

>>> print(net_connect.find_prompt()) <= need to do something here
Cisco
>>> 

>>> print(net_connect.send_command('sh run | i host')) <= need to do something here
Cisco
>>> 

Python 3 Cleaner: Python 3 清洁剂:

#print hotname without #
hostname = net_connect.find_prompt()[:-1]   

print(hostname)

# print output without the word "hostname"
output = net_connect.send_command('sh run | i host')

for line in output:
    if "hostname" in line:
        print(line.strip("hostname"))        
    print(line)

find_prompt by default should return you either hostnem# (privileged) or hostname> - it's the whole idea behind it. find_prompt 默认应该返回 hostnem#(特权)或 hostname> - 这是它背后的全部想法。 As this is just a string, you can find a way around it like:由于这只是一个字符串,您可以找到一种解决方法,例如:

output = net_connect.find_prompt()
output = output.replace('#','')
print(output )

or或者

output = net_connect.send_command('sh run | i host')) 
output = output.split()
hostname = output[1]
print(hostname)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM