Advertisement
Painlover

Untitled

Dec 10th, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. import ftplib
  2.  
  3. def connect_ftp(server, username, password):
  4.     """
  5.    Membuat koneksi ke server FTP dan login.
  6.    """
  7.     try:
  8.         ftp = ftplib.FTP(server)
  9.         ftp.login(user=username, passwd=password)
  10.         print(f"Berhasil terhubung ke {server}")
  11.         return ftp
  12.     except ftplib.error_perm as e:
  13.         print(f"Login gagal: {e}")
  14.         exit(1)
  15.     except Exception as e:
  16.         print(f"Kesalahan koneksi: {e}")
  17.         exit(1)
  18.  
  19.  
  20. def list_directory(ftp):
  21.     """
  22.    Menampilkan daftar file di direktori server FTP.
  23.    """
  24.     try:
  25.         print("Daftar file di direktori server:")
  26.         ftp.retrlines("LIST")
  27.     except Exception as e:
  28.         print(f"Kesalahan saat membaca direktori: {e}")
  29.  
  30.  
  31. def upload_file(ftp, local_file, remote_file):
  32.     """
  33.    Mengunggah file ke server FTP.
  34.    """
  35.     try:
  36.         with open(local_file, "rb") as f:
  37.             ftp.storbinary(f"STOR {remote_file}", f)
  38.         print(f"File {local_file} berhasil diunggah sebagai {remote_file}.")
  39.     except Exception as e:
  40.         print(f"Kesalahan saat mengunggah file: {e}")
  41.  
  42.  
  43. def download_file(ftp, remote_file, local_file):
  44.     """
  45.    Mengunduh file dari server FTP.
  46.    """
  47.     try:
  48.         with open(local_file, "wb") as f:
  49.             ftp.retrbinary(f"RETR {remote_file}", f.write)
  50.         print(f"File {remote_file} berhasil diunduh sebagai {local_file}.")
  51.     except Exception as e:
  52.         print(f"Kesalahan saat mengunduh file: {e}")
  53.  
  54.  
  55. def main():
  56.     server = "192.168.56.105"
  57.     username = "anehinnn"
  58.     password = "1234"
  59.  
  60.     ftp = connect_ftp(server, username, password)
  61.  
  62.     try:
  63.         list_directory(ftp)
  64.  
  65.         upload_file(ftp, "220010178_ibnu.txt", "ibnu_upload.txt")
  66.  
  67.         download_file(ftp, "ibnu_upload.txt", "local_download.txt")
  68.  
  69.         list_directory(ftp)
  70.     finally:
  71.         ftp.quit()
  72.         print("Koneksi FTP ditutup.")
  73.  
  74.  
  75. if __name__ == "__main__":
  76.     main()
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement