使用SSH包写了一个SCP文件到远程服务器的东东

func sendFile(client *ssh.Client, src string, dest string) error {
    session, err := client.NewSession()
    if err != nil {
        return err
    }
    defer session.Close()
    go func() error {
        w, errs := session.StdinPipe()
        if errs != nil {
            return errs
        }
        defer w.Close()
        fileSrc, srcErr := os.Open(src)
        if srcErr != nil {
            return srcErr
        }
        srcStat, fileErr := fileSrc.Stat()
        if fileErr != nil {
            return fileErr
        }
        fmt.Fprintln(w, "C0644", srcStat.Size(), filepath.Base(dest))
        io.Copy(w, fileSrc)
        fmt.Fprint(w, "x00") // 传输以x00结束
        return nil
    }()
    if err := session.Run("/usr/bin/scp -qrt " + filepath.Dir(dest)); err != nil {
        return err
    }
    return nil
}

在服务器上执行一个PY脚本

func execCmd(client *ssh.Client, cmd string) (error, string) {
    sessions, err := client.NewSession()
    if err != nil {
        return err, ""
    }
    defer sessions.Close()
    str, errc := sessions.CombinedOutput(cmd)
    return errc, string(str)
}

结果

SCP文件是正常的,在执行PY脚本的时候代码也全部执行了,不过输出的结果不一致
和在服务器上直接执行python xxx.py par1 par2 不一样
xxx.py

os.system(‘tar zxvf xxx.tar.gz’)//这个会显示解压文件的路径
ptint(“start”)
os.system(cp xxx.class)
print(“stelp 2”)
os.system(‘tar zcvf xxx.tar.gz ./’)//这个会显示路径

GO得到的结果

显示tar zxvf 的结果
显示tar zcvf 的结果
print(start)
print(step 2)

没闹明白为啥这样的 是不是和PY调用系统命令有关系.

index.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import web
import blog
render = web.template.render('templates/')
urls=(
    '/blog',blog.app_blog,
    '/','index',
)

class index:
    def GET(self):
        name='test'
        #i = web.input(name=None)
        return render.index(name)



if __name__ == "__main__":
    app=web.application(urls,globals())
    app.run()

blog.py
继续阅读

用python执行普通的shell命令,和需要交互的命令

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import commands,pexpect,os,sys
### 1527 or 1331
reg=sys.argv[1]
###执行命令
status,content=commands.getstatusoutput("sha256sum test.csv > hash.txt")
###执行交互命令
cmd='scp hash.txt username@testhost.com:'
child=pexpect.spawn(cmd,timeout=None)
child.expect('y/N')
###类似终端输入yes
child.sendline('yes')
#child.interact()
child.close()

#!/usr/bin/python
# -*- coding: utf-8 -*- 
import imaplib,base64,email
imap=imaplib.IMAP4('imap.qq.com')
imap.debug=3
imap.login('8182@qq.com','123')
imap.select('INBOX')
result,data=imap.search(None,'UNSeen')
for num in data[0].split():
        typ,data=imap.fetch(num,'(RFC822)')
        emsg=email.message_from_string(data[0][1])
        subject,ecode=email.Header.decode_header(emsg["subject"])[0]
        fromuser=email.utils.parseaddr(emsg.get("from"))[1]
        if ecode=='gb18030':
                subject=subject.decode('gb2312').encode('utf8');
        for part in emsg.walk():
                print part.get_content_type()
                if part.get_content_type()=="text/plain":
                        body=part.get_payload(decode=True)
                        mailtype=part.get_content_charset()
                        if mailtype=='gb2312' or mailtype=='gb18030':
                                body=body.decode('gb2312').encode('utf-8')
                        else:
                                body=body.decode('utf-8')
                        print body
                        break
imap.logout()
#imap.close()
print "over"

#!/usr/bin/python
# -*- coding: utf-8 -*- 
import poplib,base64,email
pop = poplib.POP3('pop.qq.com')
pop.set_debuglevel(1)
pop.user('8180@qq.com')
pop.pass_('123')
num,total_size=pop.stat()
print num,total_size
print pop.list()
if num > 0:
        numMessage=len(pop.list()[1])
        for i in range(numMessage):
                mailsrc='n'.join([l for l in pop.retr(i+1)[1]])
                emsg=email.message_from_string(mailsrc)
                subject=emsg.get("subject")
                msgheader=email.Header.Header(subject)
                msgheader=email.Header.decode_header(msgheader)
                subject=msgheader[0][0]
                fromuser=email.utils.parseaddr(emsg.get("from"))[1]
                print subject,fromuser
                mailtype=emsg.get_content_charset()
                body=emsg.get_payload()
                if mailtype=='utf-8':
                        body=base64.decodestring(body)
                elif mailtype=='gb2312':
                        body=body.decode('gb2312').encode('utf8')
                else:
                        pass
                #pop.dele(i+1)
                print emsg.is_multipart()
                print body
pop.quit()
print "over"

初步实现这个效果,细节有待研究!

这是介绍的第三款LINUX下的GUI客户端软件了

第一款 SMARNSVN:https://www.ciphp.com/2011/08/701

第二款RABBITVCS :https://www.ciphp.com/2012/07/871

今天这款软件是基于PYTHON开发的,要求安装pysvn,wxpython

官方网站:http://pysvn.tigris.org/

下载地址:http://pysvn.tigris.org/project_downloads.html (pysvn WorkBench 1.6.6)

截图:是直接打开的工作副本

继续阅读

下载对应py3k的包,在本地安装

下载地址:http://pypi.python.org/pypi/MySQL-Connector/0.3.2  这个地址失效了

2012-09-13:早前就发现MYSQL官方发布了一个python的模块
模块主页:http://dev.mysql.com/usingmysql/python/
下载地址:http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-1.0.6b2.zip
不过还是测试版的。

安装命令:python3 setup.py install
连接代码
继续阅读

import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("%s wrote:" % self.client_address[0])
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.send(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

来自官方帮助文档的代码,后面的是PY2.7的代码
继续阅读

从TXT文本转换数据到MYSQL数据库,接触一段时间python了 第一次写东西 用的是Python2.7
本来要用PY3K的,结果用的数据库链接不支持3K,在网上下载了一个3K的MYSQL驱动,结果编译失败。

#!/usr/bin/python
#coding=utf-8
import _mysql,sys,io
def addCity(prov,city,tel,post):
    try:
        conn=_mysql.connect("192.168.1.99",'php','php');
        conn.query("set names utf8");
        conn.query("insert into `domain`.`postcode`(Province,City,TelCode,
            PostCode)values('"+prov+"','"+city+"','"+tel+"','"+post+"')");
        result=conn.use_result();
        #print("version:%s" % result.fetch_row()[0])
        conn.close()
    except _mysql.Error,e:
        print("Error %d:%s" % (e.args[0],e.args[1]))
        sys.exit(1)
if __name__=="__main__":
    f = open("data.txt", "r")
    for line in f:
        content=line.split(",");
        print content[0],content[2]
        addCity(content[0],content[1],content[2],content[3]);
    f.close()