It is used when defining the processing to be performed only by the with
block of Python.
Example:
with
no block
f = open('hoge.txt', 'w')
f.write('hoge\n')
f.close()
There is a with
block
with open('hoge.txt', 'w') as f:
f.write('hoge\n')
Connect to the server only within the with
block using the paramiko package
import os
from contextlib import contextmanager
import paramiko
def connect_ssh(host, username=None, password=None):
return _connect_ssh_context(host, username, password)
@contextmanager
def _connect_ssh_context(host, username, password):
try:
#Preprocessing
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.connect(host, username=username, password=password)
yield ssh #Variables you want to receive with as
finally:
#Post-processing
ssh.close()
with connect_ssh('server', 'username') as f:
_, stdout, stderr = f.exec_command('ls')
print(stdout.read())
Recommended Posts