【发布时间】:2018-10-26 11:58:04
【问题描述】:
一些背景: 我们目前在由我们的托管合作伙伴托管的 FTP 服务器上接收来自多个数据供应商的文件。作为新项目的一部分,我们正在设置 Azure 函数。此功能在我们的托管合作伙伴为 VPN/专用网络访问设置的资源组中运行。此函数是用 Azure 函数替换 Excel/VBA 中的多个旧程序过程中的第一步。
我们需要将文件从 FTP 服务器移动到另一个内部(文件)服务器(以支持一些遗留程序)。 FTP 服务器位于 DMZ 中,因此不像文件服务器那样属于域。
现在我已经用谷歌搜索了几个小时来寻找解决方案,并相信我已经使用 https://stackoverflow.com/a/295703/998791 和 https://stackoverflow.com/a/1197430/998791 找到了它
public sealed class NetworkConnection : IDisposable
{
private string _uncShare;
public NetworkConnection(string uncShare, NetworkCredential credentials)
{
var nr = new Native.NETRESOURCE
{
dwType = Native.RESOURCETYPE_DISK,
lpRemoteName = uncShare
};
var userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
int result = Native.WNetUseConnection(IntPtr.Zero, nr, credentials.Password, userName, 0, null, null, null);
if (result != Native.NO_ERROR)
{
throw new Win32Exception(result);
}
_uncShare = uncShare;
}
public void Dispose()
{
if (!string.IsNullOrEmpty(_uncShare))
{
Native.WNetCancelConnection2(_uncShare, Native.CONNECT_UPDATE_PROFILE, false);
_uncShare = null;
}
}
private class Native
{
public const int RESOURCETYPE_DISK = 0x00000001;
public const int CONNECT_UPDATE_PROFILE = 0x00000001;
public const int NO_ERROR = 0;
[DllImport("mpr.dll")]
public static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID,
int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);
[DllImport("mpr.dll")]
public static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);
[StructLayout(LayoutKind.Sequential)]
public class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
}
}
用法:
using (new NetworkConnection(ftpServerSettings.UNCPath, new NetworkCredential(ftpServerSettings.UserName, ftpServerSettings.Password, ftpServerSettings.Domain)))
{
using (new NetworkConnection(fileServerSettings.UNCPath, new NetworkCredential(fileServerSettings.UserName, fileServerSettings.Password, fileServerSettings.Domain)))
{
handler.HandleFolders(bankDataRepository.GetFolderSettings());
}
}
在本地运行时,它工作正常,但从 Azure 运行时,我得到一个 System.ComponentModel.Win32Exception 并显示“访问被拒绝”消息。
我不确定 Azure Functions 中是否允许 DllImport,如果我需要 FullTrust(我在某个地方看到了一些关于此的内容)或者问题是否出在服务器上的权限上。
有人可以赐教吗?
【问题讨论】:
-
混合连接管理器和 SFTP 可以参考这个answer
-
@prvn 也可以不使用混合连接管理器,只使用 SFTP(或简单的 FTP)。这就是我最终做的事情(虽然为了更好的安全性,在 Azure 中有一个 VNET,但这是可选的)
标签: azure-functions azure-functions-runtime