defexecute_command(self,ssh):""" 명령어 실행 메서드 """# SSH 접속 클라이언트 루트디렉토리 경로의 파일 리스트 확인
stdin, stdout, stderr = ssh.exec_command("ls -l /")
lines :list= stdout.readlines()for line in lines:print(line.replace('\n',''))
파일 업로드하기
deffile_upload(self,ssh):""" 파일 업로드 메서드 """try:# sftp 객체 생성
sftp = ssh.open_sftp()# 업로드 할 파일 경로 지정
path = os.path.dirname(os.path.abspath(__file__))+'/secrets'# 파일 업로드
sftp.put(f'{os.path.join(path,".conn_info.json")}','/home/user-01/conn_info.json')print(f'sftp upload Success!.\n')except Exception as err:print(f'File Upload Error!\n{err}')
파일 다운로드하기
deffile_download(self,ssh):""" 파일 다운로드 메서드 """try:# sftp 객체 생성
sftp = ssh.open_sftp()# 경로 없는 경우 생성
path ='./download'ifnot os.path.exists(path):
os.mkdir(path)# 다운로드
sftp.get('/home/user-01/conn_info.json',os.path.join(path,'.conn_info.json'))print(f'sftp Download Success!.\n')except Exception as err:print(f'File Download Error!\n{err}')
위 내용을 응용하여 리눅스 서버 용량 체크하기
마운트 용량 체크 스크립트 작성
defexecute_command(self,ssh):""" 명령어 실행 메서드 """
stdin, stdout, stderr = ssh.exec_command("df -h")
lines :list= stdout.readlines()
datas =list()for line in lines:
dic =dict()# 맨 첫 행 continue 처리if re.match('[A-Z]',line):continue
all_lines =[all_line for all_line instr(line.replace('\n','')).split(' ')if all_line]# 사용량
dic['used']= all_lines[-2]# 마운트 위치
dic['mountd']= all_lines[-1]
datas.append(dic)[print(data)for data in datas]