사용자 도구

사이트 도구


ssh

문서의 이전 판입니다!


SSH

SSH timeout

/etc/ssh/sshd_config 수정(서버 쪽)

ClientAliveInterval 120  # 120초마다 확인하는 패킷을 보냄
ClientAliveCountMax 720  # 720번 이상 응답이 없을 때만 접속을 종료

/etc/ssh/ssh_config 수정(클라이언트 쪽), ~/.ssh/config도 설정 가능

Host *
    TCPKeepAlive yes
    ServerAliveInterval 120  # 120초마다 확인하는 패킷을 보냄
    ServerAliveCountMax 720  # 720번 이상 응답이 없을 때만 접속을 종료

password 없이 로그인

(클라이언트에서) 키 생성

ssh-keygen -t rsa

(클라이언트에서 서버에) 키 복사

ssh-copy-id -i ${HOME}/.ssh/id_rsa.pub {server-id}@{server-ip}

# 클라이언트의 id_rsa.pub 파일내용을 서버의 .ssh/authorized_keys 에 추가
# 만약 서버에 원격접속이 힘든경우 (예. termux)
# 클라이언트에서 python -m http.server 로 웹서버를 띄우고 
# 서버에서 wget으로 pub 파일을 다운받아 저장하고
# cat id_rsa.pub >> .ssh/authorized_keys 를 입력하여 키를 추가할 수 있음

(클라이언트에서) 접속

ssh {server-id}@{server-ip}

Port Fowarding을 이용해서 외부에서 접속

외부에서 접속하고자 하는 서버에서 실행

ssh -R 2222:localhost:22 {server-id}@{server-ip}

# {server-ip} 는 외부에서 접속이 가능한 서버

외부의 클라이언트에서에서 로컬 포트 포워딩으로 서버 접속

ssh -L 2223:localhost:2222 {server-id}@{server-ip}

다른 창에서 로컬호스트에 접속

ssh localhost -p 2223

또는, 외부 컴퓨터에서 서버에 접속 후 로컬의 2222에 접속

ssh {server-id}@{server-ip}
ssh localhost -p 2222

클라이언트의 ~/.ssh/config 에 다음 내용 추가

Host *
    ServerAliveInterval 120
lab.py
import argparse
from subprocess import run
from shlex import split
from socket import gethostname
import time
from colorama import Fore, init
from tqdm import trange
 
SERVER = '${SERVER}'
init(autoreset=True)
 
parser = argparse.ArgumentParser()
parser.add_argument('-P', '--port', default=2222)
args = parser.parse_args()
 
nx = gethostname()
cmd = 'ssh -R {}:localhost:22 {}'.format(args.port, SERVER)
 
while True:
    print('CMD:', cmd)
    print(Fore.LIGHTBLUE_EX + 'Connecting..')
    rus = run(split(cmd))
    print(Fore.LIGHTRED_EX + 'Disconnected, retry after 30 sec.')
    for _ in trange(30):
        time.sleep(1)

SSHFS

sshfs 설치

sudo apt install sshfs

마운트

  • /etc/fuse.conf에서 user_allow_other 설정
sshfs {server-id}@{server-ip}:{target-dir} {mount-dir} -o allow_other -o reconnect -o nonempty

언마운트

fusermount -u {mount}

자동 마운트

  • fstab에 설정
  • 또는 .bashrc에 마운트 명령 추가

Windows 용

net use S: \\sshfs\rex83128312@{IP}

SSH remote command

암호없이 로그인 설정 후 사용

ssh {ip} {command}

여러줄 명령어 실행

# 예) working directory 변경후, 명령어 실행
ssh {ip} 'cd /working/directory ; python main.py'

python script에서 실행

import subprocess
import shlex
from pprint import pprint
 
 
def get_output(ssh):
    out, _ = ssh.communicate()
    lines = out.split('\n')
    return lines[-3], float(lines[-2].split(':')[1])
 
 
ip_addresses = ['192.168.0.xxx', '192.168.0.xxx']
cmd = "ssh {ip} 'cd /working/directory ; python main.py'"
 
# ssh_list = [subprocess.Popen(shlex.split(cmd.format(ip=ip_address))) for ip_address in ip_addresses]
# [ssh.wait() for ssh in ssh_list]
 
ssh_list = [subprocess.Popen(shlex.split(cmd.format(ip=ip_address)),
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE) for ip_address in ip_addresses]
 
outputs = [(idx, get_output(ssh)) for idx, ssh in enumerate(ssh_list)]
pprint(outputs)

port 변경

  • /etc/ssh/sshd_config의 Port 22 변경

ssh config

~/.ssh/config 에 Host 설정을 저장

Host *
  TCPKeepAlive yes
  ServerAliveInterval 30
  ServerAliveCountMax 720

Host n2
  HostName 192.168.0.102
  User {id}
  IdentityFile /home/{id}/.ssh/id_rsa.pem
ssh.1578534188.txt.gz · 마지막으로 수정됨: 2024/03/23 02:37 (바깥 편집)