免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1663 | 回复: 6

python函数问题 [复制链接]

论坛徽章:
0
发表于 2012-06-25 15:43 |显示全部楼层
小弟是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")也没有成功执行,这是为什么呢?


论坛徽章:
10
亥猪
日期:2013-08-15 14:50:422015年迎新春徽章
日期:2015-03-04 09:58:112015亚冠之吉达阿赫利
日期:2015-07-21 09:49:08神斗士
日期:2015-11-20 14:07:3815-16赛季CBA联赛之江苏
日期:2017-08-17 14:04:21CU大牛徽章
日期:2013-09-18 15:15:45CU大牛徽章
日期:2013-09-18 15:16:09CU十二周年纪念徽章
日期:2013-10-24 15:41:34巳蛇
日期:2014-03-29 19:05:3215-16赛季CBA联赛之辽宁
日期:2022-04-08 16:41:44
发表于 2012-06-25 18:26 |显示全部楼层
本帖最后由 千年老狼 于 2012-06-25 18:31 编辑

是不是你看的教程是2。7的而电脑是3。0以上的?
我也是新手不对莫怪
@ulovko

论坛徽章:
0
发表于 2012-06-26 08:21 |显示全部楼层
额,是版本的原因吗?
我也是在网上搜一些教程,应该都是比较老的,我的系统python也比较老是 2.4的版本。

论坛徽章:
0
发表于 2012-06-26 09:49 |显示全部楼层
你的file_run 应该是本地运行了而没有在远程运行
至于服务没有启动成功你可以打印stderr.readlines看看

论坛徽章:
0
发表于 2012-06-26 13:48 |显示全部楼层
zyd320 发表于 2012-06-26 09:49
你的file_run 应该是本地运行了而没有在远程运行
至于服务没有启动成功你可以打印stderr.readlines看看


有道理,我觉得也是这样
那如果要让这个功能可以实现,应该怎么办呢?把整个file_fun()的功能写到exe_ssh()里边吗?

论坛徽章:
0
发表于 2012-06-26 15:39 |显示全部楼层
你可以
将配置下载到本地修改在上传到服务器。
或者
  1. stdin,stdout,stderr=s.exec_command("sed -i '16a server time.abc.com prefer' /etc/ntp.conf")
  2. if stderr:
  3.     print stderr.readlines
复制代码
回复 5# shichunda


   

论坛徽章:
0
发表于 2012-06-26 15:54 |显示全部楼层
好吧,看来也只能这样解决了,谢谢。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP