我开始学习devops和Python编码(我是一名网络工程师,不是一名开发人员),所以如果我的问题过于基本,我会提前道歉。在
我正在写一个代码,把一个完全限定的域名转换成一个ip地址列表,然后程序应该把这些ip写入一个文件,把它们插入一个不同的行,除此之外,每一个新行还应该包含一些预定义的字符串“network device commands”。在
然后,我的代码将获取这个文件,连接(使用NETCONF)到一些网络设备并执行文件中的命令。在
现在,我的代码是:
import os
import socket
from netconf.os import Device
from netconf.utils.config import Config
# Variables Declaration Section
domain = raw_input('Enter the domain name you want to resolve: ')
device_management = raw_input('Enter the device Management IP address: ')
device_user = raw_input('Enter the device admin account: ')
device_pass = raw_input('Enter the device admin account password: ')
# DNS Resolution Section
ip_list = list()
try:
ip_list = socket.gethostbyname_ex(domain)
print "Resolving addresess"
except socket.gaierror, err:
print "Domain resolution error, please check network connectivity"
ip_list = ()
if ip_list != ():
print "Domain name resolved"
else:
print "Error: List of IP address is empty"
exit()
# Initial list clean up section (ip_list contains ips and words, need to filter)
cleaned_ip_list = ip_list[2]
# Creating the Device Template Config file
file = open("device_config.txt", "w")
for i in range(len(cleaned_ip_list)):
a=None
file.write( "'set address '+'a'+(a+1)+' '+cleaned_ip_list[i]\n")
file.close()
我现在的问题是文件.写入行,只需按照代码中的原样编写行,而不是插入变量并将它们与字符串连接起来。在
我尝试了几种不同的组合,但没有成功。在
您当前正在编写单个字符串文本,而不是串联字符串。我建议使用
format()
方法。在大括号
{}
将替换为format()
的相应参数。在我觉得应该是那样的。在
让我们看看问题所在:
您正试图编写
^{pr2}$String
的部分内容,其中散布着更改的值(variables
)。在相关问题 更多 >
编程相关推荐