Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active May 3, 2022
Embed
What would you like to do?
Use paramiko to connect to git repository over ssh.
#!/usr/bin/env python
################################################################################
# MIT License
#
# Copyright (c) 2021 Hajime Nakagami
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
################################################################################
"""
Use paramiko to connect to GitHub repository over ssh.
1. ssh-keygen -t ed25519 -C "your_email@example.com"
2. register public ssh key https://github.com/settings/keys
3. pip install paramiko
4. GIT_SSH=/path/to/gitssh.py git clone git@github.com:someone/somewhat.git
"""
import sys
import os
import select
import paramiko
KEY_FILENAME = os.path.join(os.environ["HOME"], ".ssh/id_ed25519")
PORT = 22
BUFSIZE = 4096*10
username, host = sys.argv[1].split("@")
command = sys.argv[2]
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, key_filename=KEY_FILENAME, port=PORT)
channel = client.get_transport().open_session(timeout=10)
channel.exec_command(command)
while not channel.closed:
if select.select([sys.stdin], [], [], 0.0)[0]:
b = os.read(sys.stdin.fileno(), BUFSIZE)
while b:
n = channel.send(b)
b = b[n:]
while channel.recv_ready():
b = channel.recv(BUFSIZE)
while b:
n = sys.stdout.buffer.write(b)
b = b[n:]
sys.stdout.flush()
while channel.recv_stderr_ready():
b = channel.recv_stderr(BUFSIZE)
while b:
n = sys.stderr.buffer.write(b)
b = b[n:]
sys.stderr.flush()
channel.close()
sys.exit(channel.recv_exit_status())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment