国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 後端開發(fā) php教程 php python ftp操作類

php python ftp操作類

Jul 25, 2016 am 08:51 AM

php python ftp操作類
  1. class Ftp {
  2. //FTP 連接資源
  3. private $link;
  4. //FTP連接時(shí)間
  5. public $link_time;
  6. //錯(cuò)誤代碼
  7. private $err_code = 0;
  8. //傳送模式{文本模式:FTP_ASCII, 二進(jìn)制模式:FTP_BINARY}
  9. public $mode = FTP_BINARY;
  10. /**
  11. 初始化類
  12. **/
  13. public function start($data)
  14. {
  15. if(empty($data['port'])) $data['port'] ='21';
  16. if(empty($data['pasv'])) $data['pasv'] =false;
  17. if(empty($data['ssl'])) $data['ssl'] = false;
  18. if(empty($data['timeout'])) $data['timeout'] = 30;
  19. return $this->connect($data['server'],$data['username'],$data['password'],$data['port'],$data['pasv'],$data['ssl'],$data['timeout']);
  20. }
  21. /**
  22. * 連接FTP服務(wù)器
  23. * @param string $host    服務(wù)器地址
  24. * @param string $username   用戶名
  25. * @param string $password   密碼
  26. * @param integer $port     服務(wù)器端口,默認(rèn)值為21
  27. * @param boolean $pasv 是否開啟被動(dòng)模式
  28. * @param boolean $ssl      是否使用SSL連接
  29. * @param integer $timeout 超時(shí)時(shí)間 
  30. */
  31. public function connect($host, $username = '', $password = '', $port = '21', $pasv = false, $ssl = false, $timeout = 30) {
  32. $start = time();
  33. if ($ssl) {
  34. if (!$this->link = @ftp_ssl_connect($host, $port, $timeout)) {
  35. $this->err_code = 1;
  36. return false;
  37. }
  38. } else {
  39. if (!$this->link = @ftp_connect($host, $port, $timeout)) {
  40. $this->err_code = 1;
  41. return false;
  42. }
  43. }
  44. if (@ftp_login($this->link, $username, $password)) {
  45. if ($pasv)
  46. ftp_pasv($this->link, true);
  47. $this->link_time = time() - $start;
  48. return true;
  49. } else {
  50. $this->err_code = 1;
  51. return false;
  52. }
  53. register_shutdown_function(array(&$this, 'close'));
  54. }
  55. /**
  56. * 創(chuàng)建文件夾
  57. * @param string $dirname 目錄名,
  58. */
  59. public function mkdir($dirname) {
  60. if (!$this->link) {
  61. $this->err_code = 2;
  62. return false;
  63. }
  64. $dirname = $this->ck_dirname($dirname);
  65. $nowdir = '/';
  66. foreach ($dirname as $v) {
  67. if ($v && !$this->chdir($nowdir . $v)) {
  68. if ($nowdir)
  69. $this->chdir($nowdir);
  70. @ftp_mkdir($this->link, $v);
  71. }
  72. if ($v)
  73. $nowdir .= $v . '/';
  74. }
  75. return true;
  76. }
  77. /**
  78. * 上傳文件
  79. * @param string $remote 遠(yuǎn)程存放地址
  80. * @param string $local 本地存放地址
  81. */
  82. public function put($remote, $local) {
  83. if (!$this->link) {
  84. $this->err_code = 2;
  85. return false;
  86. }
  87. $dirname = pathinfo($remote, PATHINFO_DIRNAME);
  88. if (!$this->chdir($dirname)) {
  89. $this->mkdir($dirname);
  90. }
  91. if (@ftp_put($this->link, $remote, $local, $this->mode)) {
  92. return true;
  93. } else {
  94. $this->err_code = 7;
  95. return false;
  96. }
  97. }
  98. /**
  99. * 刪除文件夾
  100. * @param string $dirname 目錄地址
  101. * @param boolean $enforce 強(qiáng)制刪除
  102. */
  103. public function rmdir($dirname, $enforce = false) {
  104. if (!$this->link) {
  105. $this->err_code = 2;
  106. return false;
  107. }
  108. $list = $this->nlist($dirname);
  109. if ($list && $enforce) {
  110. $this->chdir($dirname);
  111. foreach ($list as $v) {
  112. $this->f_delete($v);
  113. }
  114. } elseif ($list && !$enforce) {
  115. $this->err_code = 3;
  116. return false;
  117. }
  118. @ftp_rmdir($this->link, $dirname);
  119. return true;
  120. }
  121. /**
  122. * 刪除指定文件
  123. * @param string $filename 文件名
  124. */
  125. public function delete($filename) {
  126. if (!$this->link) {
  127. $this->err_code = 2;
  128. return false;
  129. }
  130. if (@ftp_delete($this->link, $filename)) {
  131. return true;
  132. } else {
  133. $this->err_code = 4;
  134. return false;
  135. }
  136. }
  137. /**
  138. * 返回給定目錄的文件列表
  139. * @param string $dirname 目錄地址
  140. * @return array 文件列表數(shù)據(jù)
  141. */
  142. public function nlist($dirname) {
  143. if (!$this->link) {
  144. $this->err_code = 2;
  145. return false;
  146. }
  147. if ($list = @ftp_nlist($this->link, $dirname)) {
  148. return $list;
  149. } else {
  150. $this->err_code = 5;
  151. return false;
  152. }
  153. }
  154. /**
  155. * 在 FTP 服務(wù)器上改變當(dāng)前目錄
  156. * @param string $dirname 修改服務(wù)器上當(dāng)前目錄
  157. */
  158. public function chdir($dirname) {
  159. if (!$this->link) {
  160. $this->err_code = 2;
  161. return false;
  162. }
  163. if (@ftp_chdir($this->link, $dirname)) {
  164. return true;
  165. } else {
  166. $this->err_code = 6;
  167. return false;
  168. }
  169. }
  170. /**
  171. * 獲取錯(cuò)誤信息
  172. */
  173. public function get_error() {
  174. if (!$this->err_code)
  175. return false;
  176. $err_msg = array(
  177. '1' => 'Server can not connect',
  178. '2' => 'Not connect to server',
  179. '3' => 'Can not delete non-empty folder',
  180. '4' => 'Can not delete file',
  181. '5' => 'Can not get file list',
  182. '6' => 'Can not change the current directory on the server',
  183. '7' => 'Can not upload files'
  184. );
  185. return $err_msg[$this->err_code];
  186. }
  187. /**
  188. * 檢測目錄名
  189. * @param string $url 目錄
  190. * @return 由 / 分開的返回?cái)?shù)組
  191. */
  192. private function ck_dirname($url) {
  193. $url = str_replace('', '/', $url);
  194. $urls = explode('/', $url);
  195. return $urls;
  196. }
  197. /**
  198. * 關(guān)閉FTP連接
  199. */
  200. public function close() {
  201. return @ftp_close($this->link);
  202. }
  203. }
復(fù)制代碼
  1. #!/usr/bin/python
  2. #coding=gbk
  3. '''
  4. ftp自動(dòng)下載、自動(dòng)上傳腳本,可以遞歸目錄操作
  5. '''
  6. from ftplib import FTP
  7. import os,sys,string,datetime,time
  8. import socket
  9. class MYFTP:
  10. def __init__(self, hostaddr, username, password, remotedir, port=21):
  11. self.hostaddr = hostaddr
  12. self.username = username
  13. self.password = password
  14. self.remotedir = remotedir
  15. self.port = port
  16. self.ftp = FTP()
  17. self.file_list = []
  18. # self.ftp.set_debuglevel(2)
  19. def __del__(self):
  20. self.ftp.close()
  21. # self.ftp.set_debuglevel(0)
  22. def login(self):
  23. ftp = self.ftp
  24. try:
  25. timeout = 60
  26. socket.setdefaulttimeout(timeout)
  27. ftp.set_pasv(True)
  28. print '開始連接到 %s' %(self.hostaddr)
  29. ftp.connect(self.hostaddr, self.port)
  30. print '成功連接到 %s' %(self.hostaddr)
  31. print '開始登錄到 %s' %(self.hostaddr)
  32. ftp.login(self.username, self.password)
  33. print '成功登錄到 %s' %(self.hostaddr)
  34. debug_print(ftp.getwelcome())
  35. except Exception:
  36. deal_error("連接或登錄失敗")
  37. try:
  38. ftp.cwd(self.remotedir)
  39. except(Exception):
  40. deal_error('切換目錄失敗')
  41. def is_same_size(self, localfile, remotefile):
  42. try:
  43. remotefile_size = self.ftp.size(remotefile)
  44. except:
  45. remotefile_size = -1
  46. try:
  47. localfile_size = os.path.getsize(localfile)
  48. except:
  49. localfile_size = -1
  50. debug_print('lo:%d re:%d' %(localfile_size, remotefile_size),)
  51. if remotefile_size == localfile_size:
  52. return 1
  53. else:
  54. return 0
  55. def download_file(self, localfile, remotefile):
  56. if self.is_same_size(localfile, remotefile):
  57. debug_print('%s 文件大小相同,無需下載' %localfile)
  58. return
  59. else:
  60. debug_print('>>>>>>>>>>>>下載文件 %s ... ...' %localfile)
  61. #return
  62. file_handler = open(localfile, 'wb')
  63. self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
  64. file_handler.close()
  65. def download_files(self, localdir='./', remotedir='./'):
  66. try:
  67. self.ftp.cwd(remotedir)
  68. except:
  69. debug_print('目錄%s不存在,繼續(xù)...' %remotedir)
  70. return
  71. if not os.path.isdir(localdir):
  72. os.makedirs(localdir)
  73. debug_print('切換至目錄 %s' %self.ftp.pwd())
  74. self.file_list = []
  75. self.ftp.dir(self.get_file_list)
  76. remotenames = self.file_list
  77. #print(remotenames)
  78. #return
  79. for item in remotenames:
  80. filetype = item[0]
  81. filename = item[1]
  82. local = os.path.join(localdir, filename)
  83. if filetype == 'd':
  84. self.download_files(local, filename)
  85. elif filetype == '-':
  86. self.download_file(local, filename)
  87. self.ftp.cwd('..')
  88. debug_print('返回上層目錄 %s' %self.ftp.pwd())
  89. def upload_file(self, localfile, remotefile):
  90. if not os.path.isfile(localfile):
  91. return
  92. if self.is_same_size(localfile, remotefile):
  93. debug_print('跳過[相等]: %s' %localfile)
  94. return
  95. file_handler = open(localfile, 'rb')
  96. self.ftp.storbinary('STOR %s' %remotefile, file_handler)
  97. file_handler.close()
  98. debug_print('已傳送: %s' %localfile)
  99. def upload_files(self, localdir='./', remotedir = './'):
  100. if not os.path.isdir(localdir):
  101. return
  102. localnames = os.listdir(localdir)
  103. self.ftp.cwd(remotedir)
  104. for item in localnames:
  105. src = os.path.join(localdir, item)
  106. if os.path.isdir(src):
  107. try:
  108. self.ftp.mkd(item)
  109. except:
  110. debug_print('目錄已存在 %s' %item)
  111. self.upload_files(src, item)
  112. else:
  113. self.upload_file(src, item)
  114. self.ftp.cwd('..')
  115. def get_file_list(self, line):
  116. ret_arr = []
  117. file_arr = self.get_filename(line)
  118. if file_arr[1] not in ['.', '..']:
  119. self.file_list.append(file_arr)
  120. def get_filename(self, line):
  121. pos = line.rfind(':')
  122. while(line[pos] != ' '):
  123. pos += 1
  124. while(line[pos] == ' '):
  125. pos += 1
  126. file_arr = [line[0], line[pos:]]
  127. return file_arr
  128. def debug_print(s):
  129. print (s)
  130. def deal_error(e):
  131. timenow = time.localtime()
  132. datenow = time.strftime('%Y-%m-%d', timenow)
  133. logstr = '%s 發(fā)生錯(cuò)誤: %s' %(datenow, e)
  134. debug_print(logstr)
  135. file.write(logstr)
  136. sys.exit()
  137. if __name__ == '__main__':
  138. file = open("log.txt", "a")
  139. timenow = time.localtime()
  140. datenow = time.strftime('%Y-%m-%d', timenow)
  141. logstr = datenow
  142. # 配置如下變量
  143. hostaddr = 'localhost' # ftp地址
  144. username = 'test' # 用戶名
  145. password = 'test' # 密碼
  146. port = 21 # 端口號
  147. rootdir_local = '.' + os.sep + 'bak/' # 本地目錄
  148. rootdir_remote = './' # 遠(yuǎn)程目錄
  149. f = MYFTP(hostaddr, username, password, rootdir_remote, port)
  150. f.login()
  151. f.download_files(rootdir_local, rootdir_remote)
  152. timenow = time.localtime()
  153. datenow = time.strftime('%Y-%m-%d', timenow)
  154. logstr += " - %s 成功執(zhí)行了備份\n" %datenow
  155. debug_print(logstr)
  156. file.write(logstr)
  157. file.close()
復(fù)制代碼


本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何在PHP中實(shí)施身份驗(yàn)證和授權(quán)? 如何在PHP中實(shí)施身份驗(yàn)證和授權(quán)? Jun 20, 2025 am 01:03 AM

tosecurelyhandleauthenticationandationallizationInphp,lofterTheSesteps:1.AlwaysHashPasswordSwithPassword_hash()andverifyusingspasspassword_verify(),usepreparedStatatementStopreventsqlineptions,andStoreSeruserDatain usseruserDatain $ _sessiveferterlogin.2.implementrole-2.imaccessccsccccccccccccccccccccccccc.

如何在PHP中安全地處理文件上傳? 如何在PHP中安全地處理文件上傳? Jun 19, 2025 am 01:05 AM

要安全處理PHP中的文件上傳,核心在於驗(yàn)證文件類型、重命名文件並限制權(quán)限。 1.使用finfo_file()檢查真實(shí)MIME類型,僅允許特定類型如image/jpeg;2.用uniqid()生成隨機(jī)文件名,存儲(chǔ)至非Web根目錄;3.通過php.ini和HTML表單限製文件大小,設(shè)置目錄權(quán)限為0755;4.使用ClamAV掃描惡意軟件,增強(qiáng)安全性。這些步驟有效防止安全漏洞,確保文件上傳過程安全可靠。

PHP中==(鬆散比較)和===(嚴(yán)格的比較)之間有什麼區(qū)別? PHP中==(鬆散比較)和===(嚴(yán)格的比較)之間有什麼區(qū)別? Jun 19, 2025 am 01:07 AM

在PHP中,==與===的主要區(qū)別在於類型檢查的嚴(yán)格程度。 ==在比較前會(huì)進(jìn)行類型轉(zhuǎn)換,例如5=="5"返回true,而===要求值和類型都相同才會(huì)返回true,例如5==="5"返回false。使用場景上,===更安全應(yīng)優(yōu)先使用,==僅在需要類型轉(zhuǎn)換時(shí)使用。

如何在PHP( - , *, /,%)中執(zhí)行算術(shù)操作? 如何在PHP( - , *, /,%)中執(zhí)行算術(shù)操作? Jun 19, 2025 pm 05:13 PM

PHP中使用基本數(shù)學(xué)運(yùn)算的方法如下:1.加法用 號,支持整數(shù)和浮點(diǎn)數(shù),也可用於變量,字符串?dāng)?shù)字會(huì)自動(dòng)轉(zhuǎn)換但不推薦依賴;2.減法用-號,變量同理,類型轉(zhuǎn)換同樣適用;3.乘法用*號,適用於數(shù)字及類似字符串;4.除法用/號,需避免除以零,並註意結(jié)果可能是浮點(diǎn)數(shù);5.取模用%號,可用於判斷奇偶數(shù),處理負(fù)數(shù)時(shí)餘數(shù)符號與被除數(shù)一致。正確使用這些運(yùn)算符的關(guān)鍵在於確保數(shù)據(jù)類型清晰並處理好邊界情況。

如何與PHP的NOSQL數(shù)據(jù)庫(例如MongoDB,Redis)進(jìn)行交互? 如何與PHP的NOSQL數(shù)據(jù)庫(例如MongoDB,Redis)進(jìn)行交互? Jun 19, 2025 am 01:07 AM

是的,PHP可以通過特定擴(kuò)展或庫與MongoDB和Redis等NoSQL數(shù)據(jù)庫交互。首先,使用MongoDBPHP驅(qū)動(dòng)(通過PECL或Composer安裝)創(chuàng)建客戶端實(shí)例並操作數(shù)據(jù)庫及集合,支持插入、查詢、聚合等操作;其次,使用Predis庫或phpredis擴(kuò)展連接Redis,執(zhí)行鍵值設(shè)置與獲取,推薦phpredis用於高性能場景,Predis則便於快速部署;兩者均適用於生產(chǎn)環(huán)境且文檔完善。

我如何了解最新的PHP開發(fā)和最佳實(shí)踐? 我如何了解最新的PHP開發(fā)和最佳實(shí)踐? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

什麼是PHP,為什麼它用於Web開發(fā)? 什麼是PHP,為什麼它用於Web開發(fā)? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

如何設(shè)置PHP時(shí)區(qū)? 如何設(shè)置PHP時(shí)區(qū)? Jun 25, 2025 am 01:00 AM

tosetTherightTimeZoneInphp,restate_default_timezone_set()functionAtthestArtofyourscriptWithavalIdidentIdentifiersuchas'america/new_york'.1.usedate_default_default_timezone_set_set()

See all articles