Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bf0aef4

Browse files
committed
add ssh modules
1 parent 4e2511f commit bf0aef4

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

test_ssh/ssh.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import paramiko
2+
import six
3+
4+
5+
class SSHClient(object):
6+
def __init__(self, host, user, password, port=None, key_contents=None,
7+
key_filename=None, timeout=None):
8+
try:
9+
self.ssh = paramiko.SSHClient()
10+
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
11+
self.host = host
12+
if key_contents:
13+
data = six.StringIO(key_contents)
14+
if "BEGIN RSA PRIVATE" in key_contents:
15+
pkey = paramiko.RSAKey.from_private_key(data)
16+
elif "BEGIN DSA PRIVATE" in key_contents:
17+
pkey = paramiko.DSSKey.from_private_key(data)
18+
else:
19+
# Can't include the key contents - secure material.
20+
raise ValueError("Invalid private key")
21+
else:
22+
pkey = None
23+
self.ssh.connect(host,
24+
username=user,
25+
password=password,
26+
port=port if port else 22,
27+
pkey=pkey,
28+
key_filename=key_filename if not pkey else None,
29+
timeout=timeout if timeout else 0)
30+
except Exception as e:
31+
print 'error'
32+
33+
def close(self):
34+
if self.ssh:
35+
self.ssh.close()
36+
37+
def exec_command(self, command):
38+
stdin, stdout, stderr = self.ssh.exec_command(command)
39+
if stderr:
40+
print 'command error'
41+
42+
return stdout
43+
44+
ssh = SSHClient('10.240.198.57', 'root', 'Passw0rd')
45+
ssh.exec_command('ls /')

test_ssh/ssh_subprocess.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import subprocess
2+
import signal
3+
from oslo_log import log
4+
5+
LOG = log.getLogger(__name__)
6+
7+
8+
def _subprocess_setup():
9+
# Python installs a SIGPIPE handler by default. This is usually not what
10+
# non-Python subprocesses expect.
11+
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
12+
13+
14+
def _subprocess_popen(args, stdin=None, stdout=None, stderr=None, shell=False,
15+
env=None, preexec_fn=_subprocess_setup, close_fds=True):
16+
return subprocess.Popen(args, shell=shell, stdin=stdin, stdout=stdout,
17+
stderr=stderr, preexec_fn=preexec_fn,
18+
close_fds=close_fds, env=env)
19+
20+
21+
class SSHClient(object):
22+
def __init__(self, host, user, passwd, script):
23+
self.host = host
24+
self.user = user
25+
self.passwd = passwd
26+
self.script = script
27+
28+
def exec_command(self, cmd):
29+
LOG.info("Exec command: %s", cmd)
30+
cmd = self.script + ' ' + self.host + ' ' + self.user \
31+
+ ' ' + self.passwd + ' ' + '"' + cmd + '"'
32+
return _subprocess_popen(cmd, shell=True,
33+
stdin=subprocess.PIPE,
34+
stdout=subprocess.PIPE,
35+
stderr=subprocess.PIPE)

0 commit comments

Comments
 (0)