详解ftp成立文件权限难点

亚洲必赢app,详解ftp创设文件权限难题

c#  ftp创建文件(非上传文件)

一、问题

1.奇葩的传说:

有一个那样的急需,admin为多少个Linux为其FTP应用创设的贰个有权力限制的用户,通过admin用户能够开始展览登陆FTP服务,登6FTP服务后,创立文件夹,该文件夹的用户和用户组都以admin,属性为75伍,即唯有admin用户才有写的权力,可是,FTP后台是通过b用户登6linux系统施行顺序上传文件到FTP服务器,由于FTP服务器的文本夹都是由admin用户成立的,且品质为75伍,b用户根本未曾写的权位,导致程序上传文件失利。

  后天项目中遇见那样个奇葩的主题素材,ftp文件传输达成后要在ftp目录下另3个文书夹下创建对应的空文件,据他们说是为着文件的完整性,既然那样说,那么就务须那样干,职员和工人遵循领导是职工的天职,壹来二去,思路有了。四个方案:一.透过ftp创造文件;二.地面创立然后在传输过去。开端认为ftp创设文件不太好整,究竟要在中距离电脑上创造文件,应该是不被允许的把。所以不得不选择另1种方案了,在本土创立文件然后在经过ftp传过去不就行了么,说干就干。首假如项目转移非常的小,就像此干了。(白干了)可是,境遇奇葩的主题材料了,传过去后还要修改文件名,还没来的及修改被迁移程序迁走了,还没来的及修改就被迁移了,所以文件名不符合要求了,那都以小事,主假诺背后的次第无法施行,传输程序报错,同步程序报错,真所谓的牵一发而动全身。所以,上边说的白干了正是那般个意思。既然境遇标题,就得消除呗,说着只好回到此前的笔触上了。那么就只可以通过第三种方案了,通过ftp创设文件。网络找了个ftpHelper可是看了真正尚未创立文件的函数,但细细看来,和上传文件挺类似的,那么就有了下边包车型地铁传说。

二、分析

二.FTPHelper类库:

这正是说化解难点的法子应该很轻便,既然admin用户成立的目录暗中同意属性为755,那么一旦将默许属性改为775,并将b用户增加到admin所属用户组里面去,难点就化解了。

亚洲必赢app 1亚洲必赢app 2

三、解决

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Net;
  6 using System.Text;
  7 using System.Text.RegularExpressions;
  8 
  9 namespace FTP_Demo
 10 {
 11     /// <summary>
 12     /// FTP帮助类
 13     /// </summary>
 14     public class FTPHelper
 15     {
 16         #region 字段
 17         string ftpURI;
 18         string ftpUserID;
 19         string ftpServerIP;
 20         string ftpPassword;
 21         string ftpRemotePath;
 22         #endregion
 23 
 24         /// <summary>  
 25         /// 连接FTP服务器
 26         /// </summary>  
 27         /// <param name="FtpServerIP">FTP连接地址</param>  
 28         /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  
 29         /// <param name="FtpUserID">用户名</param>  
 30         /// <param name="FtpPassword">密码</param>  
 31         public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
 32         {
 33             ftpServerIP = FtpServerIP;
 34             ftpRemotePath = FtpRemotePath;
 35             ftpUserID = FtpUserID;
 36             ftpPassword = FtpPassword;
 37             ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
 38         }
 39 
 40         /// <summary>  
 41         /// 上传  
 42         /// </summary>   
 43         public void Upload(string filename)
 44         {
 45             FileInfo fileInf = new FileInfo(filename);
 46             FtpWebRequest reqFTP;
 47             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
 48             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
 49             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
 50             reqFTP.KeepAlive = false;
 51             reqFTP.UseBinary = true;
 52             reqFTP.ContentLength = fileInf.Length;
 53             int buffLength = 2048;
 54             byte[] buff = new byte[buffLength];
 55             int contentLen;
 56             FileStream fs = fileInf.OpenRead();
 57             try
 58             {
 59                 Stream strm = reqFTP.GetRequestStream();
 60                 contentLen = fs.Read(buff, 0, buffLength);
 61                 while (contentLen != 0)
 62                 {
 63                     strm.Write(buff, 0, contentLen);
 64                     contentLen = fs.Read(buff, 0, buffLength);
 65                 }
 66                 strm.Close();
 67                 fs.Close();
 68             }
 69             catch (Exception ex)
 70             {
 71                 throw new Exception(ex.Message);
 72             }
 73         }
 74 
 75         /// <summary>  
 76         /// 下载  
 77         /// </summary>   
 78         public void Download(string filePath, string fileName)
 79         {
 80             try
 81             {
 82                 FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
 83                 FtpWebRequest reqFTP;
 84                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
 85                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
 86                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
 87                 reqFTP.UseBinary = true;
 88                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
 89                 Stream ftpStream = response.GetResponseStream();
 90                 long cl = response.ContentLength;
 91                 int bufferSize = 2048;
 92                 int readCount;
 93                 byte[] buffer = new byte[bufferSize];
 94                 readCount = ftpStream.Read(buffer, 0, bufferSize);
 95                 while (readCount > 0)
 96                 {
 97                     outputStream.Write(buffer, 0, readCount);
 98                     readCount = ftpStream.Read(buffer, 0, bufferSize);
 99                 }
100                 ftpStream.Close();
101                 outputStream.Close();
102                 response.Close();
103             }
104             catch (Exception ex)
105             {
106                 throw new Exception(ex.Message);
107             }
108         }
109 
110         /// <summary>  
111         /// 删除文件  
112         /// </summary>  
113         public void Delete(string fileName)
114         {
115             try
116             {
117                 FtpWebRequest reqFTP;
118                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
119                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
120                 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
121                 reqFTP.KeepAlive = false;
122                 string result = String.Empty;
123                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
124                 long size = response.ContentLength;
125                 Stream datastream = response.GetResponseStream();
126                 StreamReader sr = new StreamReader(datastream);
127                 result = sr.ReadToEnd();
128                 sr.Close();
129                 datastream.Close();
130                 response.Close();
131             }
132             catch (Exception ex)
133             {
134                 throw new Exception(ex.Message);
135             }
136         }
137 
138         /// <summary>  
139         /// 获取当前目录下明细(包含文件和文件夹)  
140         /// </summary>  
141         public string[] GetFilesDetailList()
142         {
143             try
144             {
145                 StringBuilder result = new StringBuilder();
146                 FtpWebRequest ftp;
147                 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
148                 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
149                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
150                 WebResponse response = ftp.GetResponse();
151                 StreamReader reader = new StreamReader(response.GetResponseStream());
152                 string line = reader.ReadLine();
153                 line = reader.ReadLine();
154                 line = reader.ReadLine();
155                 while (line != null)
156                 {
157                     result.Append(line);
158                     result.Append("\n");
159                     line = reader.ReadLine();
160                 }
161                 result.Remove(result.ToString().LastIndexOf("\n"), 1);
162                 reader.Close();
163                 response.Close();
164                 return result.ToString().Split('\n');
165             }
166             catch (Exception ex)
167             {
168                 throw new Exception(ex.Message);
169             }
170         }
171 
172         /// <summary>  
173         /// 获取FTP文件列表(包括文件夹)
174         /// </summary>   
175         private string[] GetAllList(string url)
176         {
177             List<string> list = new List<string>();
178             FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
179             req.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
180             req.Method = WebRequestMethods.Ftp.ListDirectory;
181             req.UseBinary = true;
182             req.UsePassive = true;
183             try
184             {
185                 using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
186                 {
187                     using (StreamReader sr = new StreamReader(res.GetResponseStream()))
188                     {
189                         string s;
190                         while ((s = sr.ReadLine()) != null)
191                         {
192                             list.Add(s);
193                         }
194                     }
195                 }
196             }
197             catch (Exception ex)
198             {
199                 throw (ex);
200             }
201             return list.ToArray();
202         }
203 
204         /// <summary>  
205         /// 获取当前目录下文件列表(不包括文件夹)  
206         /// </summary>  
207         public string[] GetFileList(string url)
208         {
209             StringBuilder result = new StringBuilder();
210             FtpWebRequest reqFTP;
211             try
212             {
213                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
214                 reqFTP.UseBinary = true;
215                 reqFTP.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
216                 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
217                 WebResponse response = reqFTP.GetResponse();
218                 StreamReader reader = new StreamReader(response.GetResponseStream());
219                 string line = reader.ReadLine();
220                 while (line != null)
221                 {
222 
223                     if (line.IndexOf("<DIR>") == -1)
224                     {
225                         result.Append(Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]);
226                         result.Append("\n");
227                     }
228                     line = reader.ReadLine();
229                 }
230                 result.Remove(result.ToString().LastIndexOf('\n'), 1);
231                 reader.Close();
232                 response.Close();
233             }
234             catch (Exception ex)
235             {
236                 throw (ex);
237             }
238             return result.ToString().Split('\n');
239         }
240 
241         /// <summary>  
242         /// 判断当前目录下指定的文件是否存在  
243         /// </summary>  
244         /// <param name="RemoteFileName">远程文件名</param>  
245         public bool FileExist(string RemoteFileName)
246         {
247             string[] fileList = GetFileList("*.*");
248             foreach (string str in fileList)
249             {
250                 if (str.Trim() == RemoteFileName.Trim())
251                 {
252                     return true;
253                 }
254             }
255             return false;
256         }
257 
258         /// <summary>  
259         /// 创建文件夹  
260         /// </summary>   
261         public void MakeDir(string dirName)
262         {
263             FtpWebRequest reqFTP;
264             try
265             {
266                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
267                 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
268                 reqFTP.UseBinary = true;
269                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
270                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
271                 Stream ftpStream = response.GetResponseStream();
272                 ftpStream.Close();
273                 response.Close();
274             }
275             catch (Exception ex)
276             { }
277         }
278 
279         /// <summary>  
280         /// 获取指定文件大小  
281         /// </summary>  
282         public long GetFileSize(string filename)
283         {
284             FtpWebRequest reqFTP;
285             long fileSize = 0;
286             try
287             {
288                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
289                 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
290                 reqFTP.UseBinary = true;
291                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
292                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
293                 Stream ftpStream = response.GetResponseStream();
294                 fileSize = response.ContentLength;
295                 ftpStream.Close();
296                 response.Close();
297             }
298             catch (Exception ex)
299             { }
300             return fileSize;
301         }
302 
303         /// <summary>  
304         /// 更改文件名  
305         /// </summary> 
306         public void ReName(string currentFilename, string newFilename)
307         {
308             FtpWebRequest reqFTP;
309             try
310             {
311                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
312                 reqFTP.Method = WebRequestMethods.Ftp.Rename;
313                 reqFTP.RenameTo = newFilename;
314                 reqFTP.UseBinary = true;
315                 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
316                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
317                 Stream ftpStream = response.GetResponseStream();
318                 ftpStream.Close();
319                 response.Close();
320             }
321             catch (Exception ex)
322             { }
323         }
324 
325         /// <summary>  
326         /// 移动文件  
327         /// </summary>  
328         public void MovieFile(string currentFilename, string newDirectory)
329         {
330             ReName(currentFilename, newDirectory);
331         }
332 
333         /// <summary>  
334         /// 切换当前目录  
335         /// </summary>  
336         /// <param name="IsRoot">true:绝对路径 false:相对路径</param>   
337         public void GotoDirectory(string DirectoryName, bool IsRoot)
338         {
339             if (IsRoot)
340             {
341                 ftpRemotePath = DirectoryName;
342             }
343             else
344             {
345                 ftpRemotePath += DirectoryName + "/";
346             }
347             ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
348         }
349 
350         /// <summary>
351         ///  创建文件
352         /// </summary>
353         /// <param name="filename">文件名</param>
354         /// <param name="text">内容</param>
355         public void CreateFile(string filename, string text)
356         {
357             int bufferLength = 1024;
358             byte[] buffer = new byte[bufferLength];
359             FtpWebRequest reqFTP;
360             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
361             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
362             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
363             reqFTP.KeepAlive = false;
364             reqFTP.UseBinary = true;
365             reqFTP.ContentLength = text.Length;
366             buffer = Encoding.Unicode.GetBytes(text);
367             using (Stream stream = reqFTP.GetRequestStream())
368             {
369                 int count = buffer.Length;
370                 while (count > 0)
371                 {
372                     if (buffer.Length < bufferLength)
373                     {
374                         bufferLength = buffer.Length;
375                     }
376                     stream.Write(buffer, 0, bufferLength);
377                     count = count - bufferLength;
378                 }
379             }
380         }
381     }
382 }

1、因为系统暗中认可的登6用户是b,为了方便测试,必要报到到admin用户,然后创立文件夹看看暗许属性是或不是变动。通过b用户su到admin用户的时候报出了 
This account is currently not available. 
错误。才想到,当时创设admin用户的时候是用户的shell是禁止登六的,这里为了便于测试,通过如下命令开启shell登陆:

View Code

  $ sudo usermod -s /bin/bash admin

三.定义ftp创设文件函数:

二、然后修改系统情形变量/etc/profile文件,设置umask为00二 (目录默许属性
777-00二=77伍,文件暗中同意属性 66陆-00二= 664),source
文件生效后,切换来admin用户成立文件夹试试:发现目录的私下认可属性成功改了,变为755了

 1   /// <summary>
 2         ///  创建文件
 3        /// </summary>
 4        /// <param name="filename">文件名</param>
 5        /// <param name="text">内容</param>
 6         public void CreateFile(string filename, string text)
 7         {
 8             int bufferLength = 1024;
 9             byte[] buffer = new byte[bufferLength];
10             FtpWebRequest reqFTP;
11             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
12             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
13             reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
14             reqFTP.KeepAlive = false;
15             reqFTP.UseBinary = true;
16             reqFTP.ContentLength = text.Length;
17             buffer = Encoding.Unicode.GetBytes(text);
18             using (Stream stream = reqFTP.GetRequestStream())
19             {
20                 int count = buffer.Length;
21                 while (count > 0)
22                 {
23                     if (buffer.Length < bufferLength)
24                     {
25                         bufferLength = buffer.Length;
26                     }
27                     stream.Write(buffer, 0, bufferLength);
28                     count = count - bufferLength;
29                 }
30             }
31         }
   drwxrwxr-x 2 admin admin 4.0K Dec 6 22:54 a

四.注意:

三、然后用admin登入FTP,新建一个文本夹看看,开掘其权力依然75五

stream.Write(buffer, 0, bufferLength);

亚洲必赢app 3

出于内容的长度有异常的大可能率低于
bufferLength,所以做了如上if管理。(在此处被坑过了,提醒一下而已!)

4、由于对FTP并面生,起先并从未想到FTP那里去,而是在捣鼓各类Linux用户组和用户权限的安装,尝试都未曾用。最后静下来稳步讨论,突然想到,用admin账户登六FTP成立的文件属性一贯是755,这里登入的只是FTP应用,没有登入到shell,所以才会不受Linux情形变量中umask的熏陶,而修改umask后的admin登六shell后创立的文件属性是775,这里登入到了shell,是依照umask的值没不平常。既然开掘了难题,那么想到FTP应该也有类似Linux 
umask的设置才对,于是找到了FTP的配置文件,果然开采了之类的参数:

 

亚洲必赢app 4

⑤、修改FTP的Umask的值为00二,重启FTP服务,开采难点一挥而就了。

注:这一次难题虽小,也比非常的慢化解了,告诫自个儿!在捣鼓一些应用服务的前,要先丰富明白和熟谙这个应用服务的素材配置等,切莫贪快,不然,出现了难点,自身都不知底从何排查。

感激阅读,希望能扶助到我们,谢谢大家对本站的支撑!

您只怕感兴趣的篇章:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图