Skip to content

Commit b190804

Browse files
author
Pan
committed
Added scp write example.
1 parent a8e0d5d commit b190804

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

examples/scp_write.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/usr/bin/python
2+
3+
"""Example script for SCP write"""
4+
5+
from __future__ import print_function
6+
7+
import argparse
8+
import socket
9+
import os
10+
import pwd
11+
import sys
12+
from datetime import datetime
13+
14+
from ssh2.session import Session
15+
16+
17+
USERNAME = pwd.getpwuid(os.geteuid()).pw_name
18+
19+
parser = argparse.ArgumentParser()
20+
21+
22+
parser.add_argument('source', help="Source file to copy")
23+
parser.add_argument('destination', help="Remote destination file to copy to")
24+
parser.add_argument('--host', dest='host',
25+
default='localhost',
26+
help='Host to connect to')
27+
parser.add_argument('--port', dest='port', default=22, help="Port to connect on", type=int)
28+
parser.add_argument('-u', dest='user', default=USERNAME, help="User name to authenticate as")
29+
30+
31+
def main():
32+
args = parser.parse_args()
33+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
34+
sock.connect((args.host, args.port))
35+
s = Session()
36+
s.handshake(sock)
37+
s.agent_auth(args.user)
38+
fileinfo = os.stat(args.source)
39+
chan = s.scp_send64(args.destination, fileinfo.st_mode & 777, fileinfo.st_size,
40+
fileinfo.st_mtime, fileinfo.st_atime)
41+
print("Starting SCP of local file %s to remote %s:%s" % (
42+
args.source, args.host, args.destination))
43+
now = datetime.now()
44+
with open(args.source, 'rb') as local_fh:
45+
for data in local_fh:
46+
chan.write(data)
47+
taken = datetime.now() - now
48+
rate = (fileinfo.st_size / (1024000.0)) / taken.total_seconds()
49+
print("Finished writing remote file in %s, transfer rate %s MB/s" % (
50+
taken, rate))
51+
52+
53+
if __name__ == "__main__":
54+
main()

0 commit comments

Comments
 (0)