使用远程管理凭据将文件复制到远程计算机

时间:2009-04-19 20:25:59

标签: c# .net copy remote-access

我正在使用C#...

我需要能够将一组文件复制到大约500台独特的计算机上。我已成功地使用LogonUser()方法来模拟具有复制文件所需权限的域帐户。文件的目标路径类似于:

\\ RemoteComputer \ C $ \ SomeFolder

我的问题是......有没有办法在不使用功能强大的域帐户的情况下执行此操作(这些计算机将来可能无法加入域)?我有每台计算机的本地管理员帐户...是否有一种简单的方法可以使用LOCAL管理员帐户而不是域帐户将文件复制到计算机?

2 个答案:

答案 0 :(得分:7)

如果我错了,请纠正我,但您可以使用LogonUser冒充本地群组,而不仅仅是域帐户。

From the net:

Imports System 
Imports System.Runtime.InteropServices 
Imports System.Security.Principal 
Imports System.Security.Permissions 
Public Class Form1 
    <DllImport("advapi32.DLL", SetLastError:=True)> _ 
    Public Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, _ 
        ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _ 
        ByRef phToken As IntPtr) As Integer 
    End Function 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
        Dim admin_token As IntPtr 
        Dim wid_current As WindowsIdentity = WindowsIdentity.GetCurrent() 
        Dim wid_admin As WindowsIdentity = Nothing 
        Dim wic As WindowsImpersonationContext = Nothing 
        Try 
            MessageBox.Show("Copying file...") 
            If LogonUser("Local Admin name", "Local computer name", "pwd", 9, 0, admin_token) <> 0 Then 
                wid_admin = New WindowsIdentity(admin_token) 
                wic = wid_admin.Impersonate() 
                System.IO.File.Copy("C:\right.bmp", "\\157.60.113.28\testnew\right.bmp", True) 
                MessageBox.Show("Copy succeeded") 
            Else 
                MessageBox.Show("Copy Failed") 
            End If 
        Catch se As System.Exception 
            Dim ret As Integer = Marshal.GetLastWin32Error() 
            MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString()) 
            MessageBox.Show(se.Message) 
        Finally 
            If wic IsNot Nothing Then 
                wic.Undo() 
            End If 
        End Try 
    End Sub 
End Class 

答案 1 :(得分:2)

WNetAddConnection2会做到这一点。只需使用空字符串作为本地设备名称,以避免映射驱动器。你还想确保完成后close the connection。我将它包装到一个实现IDisposable的NetworkConnection类中。