프로그래밍/Python
[Python] Paramiko GSSAPI 사용법
vince joe
2023. 10. 9. 01:09
GSSAPI(Generic Security Service API)란 인증 API를 말한다.
pip install "paramiko[gssapi]"
파이썬 ssh 라이브러리인 paramiko에서 GSS-API/Kerberos 등등의 기능을 사용하려면, extra flavor로 설치해야 한다. gss-api와 유사한 Microsoft의 SSPI도 지원한다고 하는데, 써보진 않았다.
(참고: https://www.paramiko.org/installing.html?highlight=gssapi#the-gssapi-extra-install-flavor)
import paramiko
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
hostname="my.server.com",
username="myusername",
gss_auth=True,
# gss_kex=True,
# gss_deleg_creds=True,
)
stdin_, stdout_, stderr_ = client.exec_command("ls -al")
print(stdout_.read().decode("utf-8"))
client.close() # dangling when exception
except paramiko.ssh_exception.AuthenticationException as e:
print(e)
사용법은 위와 같다. gss 옵션이 여러가지 있는데 필요한 경우 Client api 문서를 확인한다.
paramiko의 주의점은 close를 잘 해줘야 한다는건데, paramiko가 with~ as~문을 지원하지 않아서 예외처리가 잘 되어 있지 않으면 close가 안될 수 있다. (위 코드도 마찬가지다)
아래처럼 래퍼 클래스를 만드는게 현재로선 차선책이다
import paramiko
class Client(paramiko.SSHClient):
def __init__(self, host, username, password=None):
super().__init__()
self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.host = host
self.username = username
self.password = password
def __enter__(self):
self.close()
self.connect(
self.host,
username=self.username,
password=self.password,
timeout=5
)
return self
def __exit__(self, type, value, traceback):
self.close()
with MyClient("host", "username") as client:
stdin, stdout, stderr = client.exec_command("ls")
print(stdout.read().decode())
(참고: https://github.com/paramiko/paramiko/issues/1298#issuecomment-538553477)
반응형