====== SSH ======
===== SSH timeout =====
/etc/ssh/sshd_config 수정(서버 쪽)
ClientAliveInterval 120 # 120초마다 확인하는 패킷을 보냄
ClientAliveCountMax 720 # 720번 이상 응답이 없을 때만 접속을 종료
* https://www.simplified.guide/ssh/disable-timeout
/etc/ssh/ssh_config 수정(클라이언트 쪽), ~/.ssh/config도 설정 가능
Host *
TCPKeepAlive yes
ServerAliveInterval 120 # 120초마다 확인하는 패킷을 보냄
ServerAliveCountMax 720 # 720번 이상 응답이 없을 때만 접속을 종료
* https://www.digitalocean.com/community/questions/how-to-increase-ssh-connection-timeout
===== password 없이 로그인 ======
{{tag>ssh}}
(클라이언트에서) 키 생성
ssh-keygen -t rsa
(클라이언트에서 서버에) 키 복사
# (1)
ssh-copy-id -i ${HOME}/.ssh/id_rsa.pub {server-id}@{server-ip}
# (2)
# 클라이언트의 id_rsa.pub 파일내용을 서버의 .ssh/authorized_keys 에 추가하면 되기 때문에,
# 클라이언트의 id_rsa.pub 파일을 서버에 복사하고 authorized_keys에 수동으로 추가해도 됨
scp ${HOME}/.ssh/id_rsa.pub {server-id}@{server-ip}:~/
ssh {server-id}@{server-ip}
cat id_rsa.pub >> .ssh/authorized_keys
rm id_rsa.pub
# (3)
# pem file 복사
cat ~/.ssh/id_rsa.pub | ssh -i "pair.pem" root@10.0.0.1 "cat - >> ~/.ssh/authorized_keys"
(클라이언트에서) 접속
ssh {server-id}@{server-ip}
- http://www.haruair.com/blog/2220
==== Windows ====
1. 클라이언트의 {HOME}/.ssh/id_rsa.pub 내용을 서버의 {HOME}/.ssh/authorized_keys에 추가
2. C:\ProgramData\ssh\sshd_config 에서 다음 두 줄을 주석처리
Match Group administrators
AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
3. ssh 서버 재시작
restart-service sshd
===== Port Fowarding을 이용해서 외부에서 접속 ======
{{tag>ssh}}
외부에서 접속하고자 하는 서버에서 실행
ssh -R 2222:localhost:22 -R 6006:localhost:6006 -R 8888:localhost:8888 {server-id}@{server-ip}
# {server-ip} 는 외부에서 접속이 가능한 서버
외부의 클라이언트에서에서 로컬 포트 포워딩으로 서버 접속
ssh -L 2223:localhost:2222 -L 6006:localhost:6006 -L 8888:localhost:8888 {server-id}@{server-ip}
다른 창에서 로컬호스트에 접속
ssh localhost -p 2223 # tb (6006), jupyter (8888)은 웹브라우저로 접속
또는, 외부 컴퓨터에서 서버에 접속 후 로컬의 2222에 접속
ssh {server-id}@{server-ip}
ssh localhost -p 2222
- [[http://linux.systemv.pe.kr/ssh-%ED%8F%AC%ED%8A%B8-%ED%8F%AC%EC%9B%8C%EB%94%A9/|SSH 포트 포워딩]]
- https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding
- [[http://qgp9.github.io/blog/2016/03/26/ssh-proxy-jump-host#%EC%B6%94%EC%B2%9C%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95---proxycommand|SSH Proxy 와 점프호스트(경유서버를 이용한 목적서버 연결)]]
- https://medium.com/dynamic-python/automatic-ssh-tunnels-6eb3ac4c2ad
클라이언트의 ~/.ssh/config 에 다음 내용 추가
Host *
ServerAliveInterval 120
- https://askubuntu.com/questions/127369/how-to-prevent-write-failed-broken-pipe-on-ssh-connection
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)
client - 방화벽 - proxy(중계서버, 접속가능한 서버) - 방화벽 - server(작업용)
* server에서 proxy로 접속
ssh -R 2222:localhost:22 {proxy_ip)
* client에서 proxy로 접속
ssh -L 2222:localhost:2222 {proxy_ip)
* client에서 server로 접속
ssh localhost -p 2222
===== SSHFS =====
[[sshfs]]
===== SSH remote command =====
{{tag>ssh}}
암호없이 로그인 설정 후 사용
ssh {ip} {command}
ssh -t {ip} {command} # interactive terminal (Error opening terminal: unknown. 에러가 발생할 때 사용)
여러줄 명령어 실행
# 예) working directory 변경후, 명령어 실행
ssh {ip} 'cd /working/directory ; python main.py'
재귀적으로 명령어 실행
# 127.0.0.1에 접속해서, 127.0.0.1에 접속해서, ping 127.0.0.1 실행
ssh 127.0.0.1 "echo 1; ssh 127.0.0.1 ""echo 2; ping 127.0.0.1"""
원격 아나콘다 환경 활성화
ssh {user}@{host} "source /home/rex8312/anaconda3/etc/profile.d/conda.sh; conda activate {virenv}; which python"
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)
* http://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-run-command-on-remote-machine-server/
==== 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
* http://www.haruair.com/blog/2219
{{tag>ssh}}