Chinaunix
标题:
python函数问题
[打印本页]
作者:
shichunda
时间:
2012-06-25 15:43
标题:
python函数问题
小弟是python新手,今天写了个脚本,运行的时候没有什么报错信息,但结果是没有成功的
#!/usr/bin/env python
import string
import re
import paramiko
import os
import socket
def file_fun():
log=open('/root/mss-python-log.txt','w')
filentp="/etc/ntp.conf"
try:
f1=open(filentp,'r')
except IOError,e:
log.write('there is no ntp.conf file')
allline1=f1.readlines()
f1.close()
#alllines.remove('0.rhel.pool.ntp.org')
allline1.insert(16,'server time.abc.com prefer\n')
myfile1=file("/etc/ntp.conf",'w')
for eachline in allline1:
print >> myfile1,eachline,
def exe_ssh():
s=paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
s.connect(hostname,port,username,password)
file_fun()
stdin,stdout,stderr=s.exec_command("service ntpd start")
stdin,stdout,stderr=s.exec_command("chkconfig ntpd on")
print hostname,":","on line and NTP have been configured!"
except socket.error:
print hostname,":","is NOT online!"
s.close()
hostname="192.168.1.1"
port=22
username="root"
password="shichunda"
exe_ssh()
我的目的是想给远端的一个服务器设置ntp服务。
我想给192.168.1.1这台服务器的/etc/ntp.conf文件添加一行,之后执行service ntpd restart和chkconfig ntpd on。测试结果是在192.168.1.1上ntpd.conf文件没有成功添加server time.abc.com prefer这行!!!
但我在192.168.1.1本地用这个脚本的file_fun()部分就没问题,能成功修改ntp.conf文件
请高手们帮我看一下哪出了问题
还有, stdin,stdout,stderr=s.exec_command("service ntpd restart")也没有成功执行,这是为什么呢?
作者:
千年老狼
时间:
2012-06-25 18:26
本帖最后由 千年老狼 于 2012-06-25 18:31 编辑
是不是你看的教程是2。7的而电脑是3。0以上的?
我也是新手不对莫怪
@ulovko
作者:
shichunda
时间:
2012-06-26 08:21
额,是版本的原因吗?
我也是在网上搜一些教程,应该都是比较老的,我的系统python也比较老是 2.4的版本。
作者:
zyd320
时间:
2012-06-26 09:49
你的file_run 应该是本地运行了而没有在远程运行
至于服务没有启动成功你可以打印stderr.readlines看看
作者:
shichunda
时间:
2012-06-26 13:48
zyd320 发表于 2012-06-26 09:49
你的file_run 应该是本地运行了而没有在远程运行
至于服务没有启动成功你可以打印stderr.readlines看看
有道理,我觉得也是这样
那如果要让这个功能可以实现,应该怎么办呢?把整个file_fun()的功能写到exe_ssh()里边吗?
作者:
zyd320
时间:
2012-06-26 15:39
你可以
将配置下载到本地修改在上传到服务器。
或者
stdin,stdout,stderr=s.exec_command("sed -i '16a server time.abc.com prefer' /etc/ntp.conf")
if stderr:
print stderr.readlines
复制代码
回复
5#
shichunda
作者:
shichunda
时间:
2012-06-26 15:54
好吧,看来也只能这样解决了,谢谢。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2